platybus-assistant 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ .venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # Node
15
+ web/node_modules/
16
+ web/dist/
17
+ src/platybus/server/static/
18
+ web/*.tsbuildinfo
19
+ # Playwright artifacts
20
+ web/playwright-report/
21
+ web/test-results/
22
+ web/blob-report/
23
+ web/playwright/.cache/
24
+
25
+ # Platybus local state and demos
26
+ .platybus/
27
+ .tmp/
28
+ *.duckdb
29
+ *.duckdb.wal
30
+
31
+ # Secrets
32
+ .env
33
+ .env.*
34
+ !.env.example
35
+
36
+ # Editors / OS
37
+ .idea/
38
+ .vscode/
39
+ .DS_Store
40
+ Thumbs.db
41
+
42
+ # Claude Code local settings
43
+ .claude/settings.local.json
44
+ .claude
45
+ # MkDocs output
46
+ site/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yaroslav Ozerov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.5
2
+ Name: platybus-assistant
3
+ Version: 0.1.0
4
+ Summary: Platybus plugin: LLM providers (Anthropic, OpenAI-compatible, Ollama) for the project assistant.
5
+ Project-URL: Homepage, https://github.com/RobbyTheFish/platybus
6
+ Project-URL: Documentation, https://robbythefish.github.io/platybus/
7
+ Project-URL: Repository, https://github.com/RobbyTheFish/platybus
8
+ Project-URL: Issues, https://github.com/RobbyTheFish/platybus/issues
9
+ Project-URL: Changelog, https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md
10
+ Author: Yaroslav Ozerov
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: anthropic,assistant,llm,openai,platybus,platybus-plugin
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: anthropic<3,>=2.14
24
+ Requires-Dist: openai<4,>=3.60
25
+ Requires-Dist: platybus>=0.1.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # platybus-assistant
29
+
30
+ LLM providers for the Platybus project assistant: the Anthropic Messages API, any
31
+ OpenAI-compatible Chat Completions API (OpenAI, OpenRouter, vLLM, LM Studio, gateways) and
32
+ a preset for a local Ollama.
33
+
34
+ A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
35
+ a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
36
+ ETL, dbt and dashboards.
37
+
38
+ ```bash
39
+ pip install platybus platybus-assistant platybus-skills
40
+ ```
41
+
42
+ Platybus discovers the plugin through the `platybus.plugins` entry point. Pick a provider
43
+ in the UI (project settings → Assistant) or in `platybus.yml`:
44
+
45
+ ```yaml
46
+ assistant:
47
+ enabled: true
48
+ provider: anthropic # or: openai, ollama
49
+ model: claude-sonnet-5-5
50
+ settings:
51
+ api_key: ${ANTHROPIC_API_KEY}
52
+ ```
53
+
54
+ API keys are secrets: keep them in `.env` or the environment, never in YAML. Documentation:
55
+ <https://robbythefish.github.io/platybus/assistant/>.
56
+
57
+ License: MIT.
@@ -0,0 +1,30 @@
1
+ # platybus-assistant
2
+
3
+ LLM providers for the Platybus project assistant: the Anthropic Messages API, any
4
+ OpenAI-compatible Chat Completions API (OpenAI, OpenRouter, vLLM, LM Studio, gateways) and
5
+ a preset for a local Ollama.
6
+
7
+ A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
8
+ a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
9
+ ETL, dbt and dashboards.
10
+
11
+ ```bash
12
+ pip install platybus platybus-assistant platybus-skills
13
+ ```
14
+
15
+ Platybus discovers the plugin through the `platybus.plugins` entry point. Pick a provider
16
+ in the UI (project settings → Assistant) or in `platybus.yml`:
17
+
18
+ ```yaml
19
+ assistant:
20
+ enabled: true
21
+ provider: anthropic # or: openai, ollama
22
+ model: claude-sonnet-5-5
23
+ settings:
24
+ api_key: ${ANTHROPIC_API_KEY}
25
+ ```
26
+
27
+ API keys are secrets: keep them in `.env` or the environment, never in YAML. Documentation:
28
+ <https://robbythefish.github.io/platybus/assistant/>.
29
+
30
+ License: MIT.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "platybus-assistant"
3
+ version = "0.1.0" # x-release-please-version
4
+ description = "Platybus plugin: LLM providers (Anthropic, OpenAI-compatible, Ollama) for the project assistant."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Yaroslav Ozerov" }]
9
+ requires-python = ">=3.12"
10
+ keywords = ["platybus", "platybus-plugin", "llm", "assistant", "anthropic", "openai"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Topic :: Database",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = [
22
+ "platybus>=0.1.0", # x-release-please-version
23
+ "anthropic>=2.14,<3",
24
+ "openai>=3.60,<4",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/RobbyTheFish/platybus"
29
+ Documentation = "https://robbythefish.github.io/platybus/"
30
+ Repository = "https://github.com/RobbyTheFish/platybus"
31
+ Issues = "https://github.com/RobbyTheFish/platybus/issues"
32
+ Changelog = "https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md"
33
+
34
+ [project.entry-points."platybus.plugins"]
35
+ assistant = "platybus_assistant:plugin"
36
+
37
+ [build-system]
38
+ requires = ["hatchling>=1.26"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/platybus_assistant"]
43
+
44
+ [tool.uv.sources]
45
+ platybus = { workspace = true }
@@ -0,0 +1,62 @@
1
+ """Platybus plugin: LLM providers for the project assistant.
2
+
3
+ - ``anthropic`` — the Anthropic Messages API (streaming, tool use, prompt caching).
4
+ - ``openai`` — any OpenAI-compatible Chat Completions API (``base_url``): OpenAI,
5
+ OpenRouter, Azure-style gateways, vLLM, LM Studio, Ollama's ``/v1``.
6
+ - ``ollama`` — the OpenAI-compatible provider preset for a local Ollama.
7
+ """
8
+
9
+ from platybus.assistant.base import AssistantProviderSpec
10
+ from platybus.plugins import Plugin
11
+ from platybus_assistant import anthropic_provider, openai_provider
12
+
13
+ ANTHROPIC = AssistantProviderSpec(
14
+ key=anthropic_provider.KEY,
15
+ title="Anthropic (Claude)",
16
+ description="Claude models through the Anthropic Messages API.",
17
+ factory=anthropic_provider.factory,
18
+ settings_model=anthropic_provider.AnthropicSettings,
19
+ models=anthropic_provider.MODELS,
20
+ default_model=anthropic_provider.DEFAULT_MODEL,
21
+ requires_key=True,
22
+ key_env="ANTHROPIC_API_KEY",
23
+ help="Create a key at https://platform.claude.com/ (Settings → API keys).",
24
+ )
25
+
26
+ OPENAI = AssistantProviderSpec(
27
+ key=openai_provider.KEY,
28
+ title="OpenAI-compatible",
29
+ description="OpenAI or any OpenAI-compatible Chat Completions API with tool calling "
30
+ "(OpenRouter, vLLM, LM Studio, gateways): set base_url and the model id.",
31
+ factory=openai_provider.openai_factory,
32
+ settings_model=openai_provider.OpenAISettings,
33
+ models=(),
34
+ default_model=None,
35
+ requires_key=False,
36
+ key_env="OPENAI_API_KEY",
37
+ help="Local servers usually need no key; hosted APIs do.",
38
+ )
39
+
40
+ OLLAMA = AssistantProviderSpec(
41
+ key=openai_provider.OLLAMA_KEY,
42
+ title="Ollama (local)",
43
+ description="A model served by a local Ollama (no key; pick a model with tool support).",
44
+ factory=openai_provider.ollama_factory,
45
+ settings_model=openai_provider.OllamaSettings,
46
+ models=("qwen3", "llama3.3", "gpt-oss"),
47
+ default_model="qwen3",
48
+ requires_key=False,
49
+ key_env=None,
50
+ help="Install Ollama, then `ollama pull qwen3`.",
51
+ )
52
+
53
+ plugin = Plugin(
54
+ name="assistant",
55
+ kind="assistant",
56
+ title="Assistant providers",
57
+ description="LLM providers for the project assistant: Anthropic, OpenAI-compatible APIs "
58
+ "and a local Ollama.",
59
+ assistants=(ANTHROPIC, OPENAI, OLLAMA),
60
+ )
61
+
62
+ __all__ = ["ANTHROPIC", "OLLAMA", "OPENAI", "plugin"]
@@ -0,0 +1,29 @@
1
+ """Shared helpers of the provider adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ import httpx2
8
+
9
+ #: Builds the HTTP client of the SDKs (tests install one with an ``httpx2.MockTransport``).
10
+ HTTP_CLIENT_FACTORY: Callable[[], httpx2.Client] | None = None
11
+
12
+
13
+ def http_client() -> httpx2.Client | None:
14
+ return HTTP_CLIENT_FACTORY() if HTTP_CLIENT_FACTORY is not None else None
15
+
16
+
17
+ def api_message(body: object, fallback: str) -> str:
18
+ """The ``error.message`` of an API error body (Anthropic and OpenAI shapes)."""
19
+ if isinstance(body, dict):
20
+ error = body.get("error", body)
21
+ message = error.get("message") if isinstance(error, dict) else None
22
+ if isinstance(message, str):
23
+ return message
24
+ return fallback
25
+
26
+
27
+ def short(text: str, limit: int = 300) -> str:
28
+ text = " ".join(str(text).split())
29
+ return text if len(text) <= limit else text[: limit - 3] + "..."
@@ -0,0 +1,201 @@
1
+ """Anthropic Messages API provider (streaming, tool use, prompt caching)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import Any, Literal
7
+
8
+ import anthropic
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+
11
+ from platybus.assistant.base import (
12
+ AssistantTurn,
13
+ ModelRequest,
14
+ ProviderContext,
15
+ ProviderEvent,
16
+ TextDelta,
17
+ ToolCall,
18
+ ToolResultsTurn,
19
+ TurnEnd,
20
+ Usage,
21
+ UserTurn,
22
+ )
23
+ from platybus.errors import AssistantError
24
+ from platybus_assistant._http import api_message, http_client, short
25
+
26
+ KEY = "anthropic"
27
+ MODELS = ("claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-5-5")
28
+ DEFAULT_MODEL = "claude-sonnet-5-5"
29
+ #: Models that accept server-side refusal fallbacks (beta), and the beta flag.
30
+ FALLBACK_MODELS = frozenset(
31
+ {
32
+ "claude-fable-5-2",
33
+ "claude-fable-5-1",
34
+ "claude-opus-5-5",
35
+ "claude-opus-5",
36
+ "claude-sonnet-5-5",
37
+ }
38
+ )
39
+ FALLBACK_BETA = "server-side-fallback-2026-07-01"
40
+
41
+
42
+ class AnthropicSettings(BaseModel):
43
+ """``assistant.settings`` for the Anthropic provider."""
44
+
45
+ model_config = ConfigDict(extra="forbid")
46
+
47
+ api_key: str | None = Field(
48
+ None, description="API key (default: the ANTHROPIC_API_KEY environment variable)."
49
+ )
50
+ base_url: str | None = Field(
51
+ None, description="API base URL, for a proxy or gateway (default: Anthropic's API)."
52
+ )
53
+ effort: Literal["low", "medium", "high", "xhigh", "max"] | None = Field(
54
+ None, description="Reasoning effort (output_config.effort); default: the model's."
55
+ )
56
+ refusal_fallback: bool = Field(
57
+ True,
58
+ description="Let the API retry a declined request on a fallback model "
59
+ "(server-side fallbacks beta; only for models that support it).",
60
+ )
61
+
62
+
63
+ def _messages(turns: Any) -> list[dict[str, Any]]:
64
+ """Provider-neutral turns → Messages API ``messages`` (same-role turns merged)."""
65
+ messages: list[dict[str, Any]] = []
66
+
67
+ def add(role: str, content: list[dict[str, Any]]) -> None:
68
+ if not content:
69
+ return
70
+ if messages and messages[-1]["role"] == role:
71
+ messages[-1]["content"].extend(content)
72
+ else:
73
+ messages.append({"role": role, "content": list(content)})
74
+
75
+ for turn in turns:
76
+ if isinstance(turn, UserTurn):
77
+ add("user", [{"type": "text", "text": turn.text}])
78
+ elif isinstance(turn, AssistantTurn):
79
+ if turn.raw_provider == KEY and isinstance(turn.raw, list) and turn.raw:
80
+ add("assistant", [dict(block) for block in turn.raw])
81
+ continue
82
+ content: list[dict[str, Any]] = []
83
+ for block in turn.blocks:
84
+ if block.get("type") == "text" and block.get("text"):
85
+ content.append({"type": "text", "text": block["text"]})
86
+ elif block.get("type") == "tool_call":
87
+ content.append(
88
+ {
89
+ "type": "tool_use",
90
+ "id": block["id"],
91
+ "name": block["name"],
92
+ "input": block.get("input") or {},
93
+ }
94
+ )
95
+ add("assistant", content)
96
+ elif isinstance(turn, ToolResultsTurn):
97
+ add(
98
+ "user",
99
+ [
100
+ {
101
+ "type": "tool_result",
102
+ "tool_use_id": r.tool_call_id,
103
+ "content": r.content or "(empty)",
104
+ "is_error": r.is_error,
105
+ }
106
+ for r in turn.results
107
+ ],
108
+ )
109
+ return messages
110
+
111
+
112
+ def _error(exc: anthropic.AnthropicError) -> AssistantError:
113
+ if isinstance(exc, anthropic.AuthenticationError):
114
+ return AssistantError("Anthropic API: authentication failed (check the API key)")
115
+ if isinstance(exc, anthropic.RateLimitError):
116
+ return AssistantError("Anthropic API: rate limited, try again later")
117
+ if isinstance(exc, anthropic.APIStatusError):
118
+ message = api_message(exc.body, exc.message)
119
+ return AssistantError(f"Anthropic API error {exc.status_code}: {short(message)}")
120
+ if isinstance(exc, anthropic.APITimeoutError):
121
+ return AssistantError("Anthropic API: the request timed out")
122
+ if isinstance(exc, anthropic.APIConnectionError):
123
+ return AssistantError("Anthropic API: cannot connect (check the network or base_url)")
124
+ return AssistantError(f"Anthropic API: {short(str(exc))}")
125
+
126
+
127
+ class AnthropicProvider:
128
+ key = KEY
129
+
130
+ def __init__(self, context: ProviderContext) -> None:
131
+ settings = context.settings
132
+ self.settings = (
133
+ settings
134
+ if isinstance(settings, AnthropicSettings)
135
+ else AnthropicSettings.model_validate({})
136
+ )
137
+ self.client = anthropic.Anthropic(
138
+ api_key=context.api_key,
139
+ base_url=self.settings.base_url or None,
140
+ timeout=context.timeout,
141
+ max_retries=2,
142
+ http_client=http_client(),
143
+ )
144
+
145
+ def _params(self, request: ModelRequest) -> dict[str, Any]:
146
+ params: dict[str, Any] = {
147
+ "model": request.model,
148
+ "max_tokens": request.max_tokens,
149
+ "system": [{"type": "text", "text": request.system}],
150
+ "messages": _messages(request.turns),
151
+ # Tools and the system prompt are stable: cache the prefix.
152
+ "cache_control": {"type": "ephemeral"},
153
+ }
154
+ if request.tools:
155
+ params["tools"] = [
156
+ {"name": t.name, "description": t.description, "input_schema": t.input_schema}
157
+ for t in request.tools
158
+ ]
159
+ if self.settings.effort:
160
+ params["output_config"] = {"effort": self.settings.effort}
161
+ return params
162
+
163
+ def stream(self, request: ModelRequest) -> Iterator[ProviderEvent]:
164
+ params = self._params(request)
165
+ try:
166
+ if self.settings.refusal_fallback and request.model in FALLBACK_MODELS:
167
+ manager: Any = self.client.beta.messages.stream(
168
+ **params, betas=[FALLBACK_BETA], fallbacks="default"
169
+ )
170
+ else:
171
+ manager = self.client.messages.stream(**params)
172
+ with manager as stream:
173
+ for event in stream:
174
+ if event.type == "text" and event.text:
175
+ yield TextDelta(event.text)
176
+ final = stream.get_final_message()
177
+ except anthropic.AnthropicError as exc:
178
+ raise _error(exc) from None
179
+ raw: list[dict[str, Any]] = []
180
+ for block in final.content:
181
+ raw.append(block.to_dict())
182
+ if block.type == "tool_use":
183
+ yield ToolCall(block.id, block.name, dict(block.input or {}))
184
+ usage = final.usage
185
+ input_tokens = (
186
+ (usage.input_tokens or 0)
187
+ + (getattr(usage, "cache_read_input_tokens", None) or 0)
188
+ + (getattr(usage, "cache_creation_input_tokens", None) or 0)
189
+ )
190
+ yield TurnEnd(
191
+ stop_reason=str(final.stop_reason or "end_turn"),
192
+ usage=Usage(input_tokens, usage.output_tokens or 0),
193
+ raw=raw,
194
+ )
195
+
196
+ def close(self) -> None:
197
+ self.client.close()
198
+
199
+
200
+ def factory(context: ProviderContext) -> AnthropicProvider:
201
+ return AnthropicProvider(context)
@@ -0,0 +1,224 @@
1
+ """OpenAI-compatible Chat Completions provider (OpenAI, OpenRouter, vLLM, LM Studio, Ollama)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterator
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Literal
9
+
10
+ import openai
11
+ from pydantic import BaseModel, ConfigDict, Field
12
+
13
+ from platybus.assistant.base import (
14
+ AssistantTurn,
15
+ ModelRequest,
16
+ ProviderContext,
17
+ ProviderEvent,
18
+ TextDelta,
19
+ ToolCall,
20
+ ToolResultsTurn,
21
+ TurnEnd,
22
+ Usage,
23
+ UserTurn,
24
+ )
25
+ from platybus.errors import AssistantError
26
+ from platybus_assistant._http import api_message, http_client, short
27
+
28
+ KEY = "openai"
29
+ OLLAMA_KEY = "ollama"
30
+ OLLAMA_URL = "http://127.0.0.1:11434/v1"
31
+ _STOP_REASONS = {
32
+ "stop": "end_turn",
33
+ "tool_calls": "tool_use",
34
+ "function_call": "tool_use",
35
+ "length": "max_tokens",
36
+ "content_filter": "refusal",
37
+ }
38
+
39
+
40
+ class OpenAISettings(BaseModel):
41
+ """``assistant.settings`` for an OpenAI-compatible API."""
42
+
43
+ model_config = ConfigDict(extra="forbid")
44
+
45
+ api_key: str | None = Field(
46
+ None, description="API key (default: the OPENAI_API_KEY environment variable)."
47
+ )
48
+ base_url: str | None = Field(
49
+ None,
50
+ description="Base URL of the Chat Completions API, e.g. https://openrouter.ai/api/v1 "
51
+ "or http://127.0.0.1:8000/v1 (default: OpenAI).",
52
+ )
53
+ max_tokens_param: Literal["max_completion_tokens", "max_tokens", "none"] = Field(
54
+ "max_completion_tokens",
55
+ description="How the output limit is sent: OpenAI uses max_completion_tokens, many "
56
+ "compatible servers max_tokens.",
57
+ )
58
+ stream_usage: bool = Field(
59
+ True, description="Ask for token usage in the stream (stream_options.include_usage)."
60
+ )
61
+
62
+
63
+ class OllamaSettings(OpenAISettings):
64
+ """``assistant.settings`` for a local Ollama (its OpenAI-compatible /v1 endpoint)."""
65
+
66
+ base_url: str | None = Field(OLLAMA_URL, description="Ollama's OpenAI-compatible endpoint.")
67
+ max_tokens_param: Literal["max_completion_tokens", "max_tokens", "none"] = Field(
68
+ "max_tokens", description="How the output limit is sent."
69
+ )
70
+ stream_usage: bool = Field(False, description="Ask for token usage in the stream.")
71
+
72
+
73
+ def _messages(system: str, turns: Any) -> list[dict[str, Any]]:
74
+ messages: list[dict[str, Any]] = [{"role": "system", "content": system}]
75
+ for turn in turns:
76
+ if isinstance(turn, UserTurn):
77
+ messages.append({"role": "user", "content": turn.text})
78
+ elif isinstance(turn, AssistantTurn):
79
+ calls = [
80
+ {
81
+ "id": block["id"],
82
+ "type": "function",
83
+ "function": {
84
+ "name": block["name"],
85
+ "arguments": json.dumps(block.get("input") or {}, ensure_ascii=False),
86
+ },
87
+ }
88
+ for block in turn.tool_calls
89
+ ]
90
+ message: dict[str, Any] = {"role": "assistant", "content": turn.text or None}
91
+ if calls:
92
+ message["tool_calls"] = calls
93
+ if turn.text or calls:
94
+ messages.append(message)
95
+ elif isinstance(turn, ToolResultsTurn):
96
+ for result in turn.results:
97
+ content = result.content or "(empty)"
98
+ if result.is_error:
99
+ content = f"ERROR: {content}"
100
+ messages.append(
101
+ {"role": "tool", "tool_call_id": result.tool_call_id, "content": content}
102
+ )
103
+ return messages
104
+
105
+
106
+ @dataclass
107
+ class _PendingCall:
108
+ id: str = ""
109
+ name: str = ""
110
+ arguments: list[str] = field(default_factory=list)
111
+
112
+
113
+ def _error(exc: openai.OpenAIError, title: str) -> AssistantError:
114
+ if isinstance(exc, openai.AuthenticationError):
115
+ return AssistantError(f"{title}: authentication failed (check the API key)")
116
+ if isinstance(exc, openai.RateLimitError):
117
+ return AssistantError(f"{title}: rate limited, try again later")
118
+ if isinstance(exc, openai.APIStatusError):
119
+ message = api_message(exc.body, exc.message)
120
+ return AssistantError(f"{title} error {exc.status_code}: {short(message)}")
121
+ if isinstance(exc, openai.APITimeoutError):
122
+ return AssistantError(f"{title}: the request timed out")
123
+ if isinstance(exc, openai.APIConnectionError):
124
+ return AssistantError(f"{title}: cannot connect (check the network or base_url)")
125
+ return AssistantError(f"{title}: {short(str(exc))}")
126
+
127
+
128
+ class OpenAICompatibleProvider:
129
+ def __init__(self, context: ProviderContext, *, key: str = KEY, title: str = "OpenAI") -> None:
130
+ self.key = key
131
+ self.title = title
132
+ settings = context.settings
133
+ self.settings = (
134
+ settings if isinstance(settings, OpenAISettings) else OpenAISettings.model_validate({})
135
+ )
136
+ self.client = openai.OpenAI(
137
+ # Local servers need no key, but the SDK requires a non-empty one.
138
+ api_key=context.api_key or "not-needed",
139
+ base_url=self.settings.base_url or None,
140
+ timeout=context.timeout,
141
+ max_retries=2,
142
+ http_client=http_client(),
143
+ )
144
+
145
+ def _params(self, request: ModelRequest) -> dict[str, Any]:
146
+ params: dict[str, Any] = {
147
+ "model": request.model,
148
+ "messages": _messages(request.system, request.turns),
149
+ "stream": True,
150
+ }
151
+ if request.tools:
152
+ params["tools"] = [
153
+ {
154
+ "type": "function",
155
+ "function": {
156
+ "name": t.name,
157
+ "description": t.description,
158
+ "parameters": t.input_schema,
159
+ },
160
+ }
161
+ for t in request.tools
162
+ ]
163
+ if self.settings.max_tokens_param != "none":
164
+ params[self.settings.max_tokens_param] = request.max_tokens
165
+ if self.settings.stream_usage:
166
+ params["stream_options"] = {"include_usage": True}
167
+ return params
168
+
169
+ def stream(self, request: ModelRequest) -> Iterator[ProviderEvent]:
170
+ calls: dict[int, _PendingCall] = {}
171
+ finish: str | None = None
172
+ usage: Usage | None = None
173
+ try:
174
+ stream = self.client.chat.completions.create(**self._params(request))
175
+ try:
176
+ for chunk in stream:
177
+ if chunk.usage is not None:
178
+ usage = Usage(
179
+ chunk.usage.prompt_tokens or 0, chunk.usage.completion_tokens or 0
180
+ )
181
+ for choice in chunk.choices:
182
+ delta = choice.delta
183
+ if delta is not None and delta.content:
184
+ yield TextDelta(delta.content)
185
+ for call in (delta.tool_calls if delta is not None else None) or []:
186
+ pending = calls.setdefault(call.index, _PendingCall())
187
+ if call.id:
188
+ pending.id = call.id
189
+ if call.function is not None:
190
+ if call.function.name:
191
+ pending.name += call.function.name
192
+ if call.function.arguments:
193
+ pending.arguments.append(call.function.arguments)
194
+ if choice.finish_reason:
195
+ finish = choice.finish_reason
196
+ finally:
197
+ stream.close()
198
+ except openai.OpenAIError as exc:
199
+ raise _error(exc, self.title) from None
200
+ for index in sorted(calls):
201
+ pending = calls[index]
202
+ text = "".join(pending.arguments).strip() or "{}"
203
+ try:
204
+ arguments = json.loads(text)
205
+ except ValueError:
206
+ arguments = {"__invalid_json__": text[:200]}
207
+ if not isinstance(arguments, dict):
208
+ arguments = {"__invalid_json__": text[:200]}
209
+ yield ToolCall(pending.id or f"call_{index}", pending.name, arguments)
210
+ stop = _STOP_REASONS.get(finish or "stop", finish or "end_turn")
211
+ if calls and stop == "end_turn":
212
+ stop = "tool_use" # some servers report "stop" after tool calls
213
+ yield TurnEnd(stop_reason=stop, usage=usage)
214
+
215
+ def close(self) -> None:
216
+ self.client.close()
217
+
218
+
219
+ def openai_factory(context: ProviderContext) -> OpenAICompatibleProvider:
220
+ return OpenAICompatibleProvider(context)
221
+
222
+
223
+ def ollama_factory(context: ProviderContext) -> OpenAICompatibleProvider:
224
+ return OpenAICompatibleProvider(context, key=OLLAMA_KEY, title="Ollama")
@@ -0,0 +1,358 @@
1
+ """Provider adapters against mocked HTTP (httpx2.MockTransport): no network, no real keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable, Iterator
7
+ from typing import Any
8
+
9
+ import httpx2
10
+ import pytest
11
+
12
+ import platybus_assistant._http as http
13
+ from platybus.assistant.base import (
14
+ AssistantTurn,
15
+ ModelRequest,
16
+ ProviderContext,
17
+ TextDelta,
18
+ ToolCall,
19
+ ToolResultContent,
20
+ ToolResultsTurn,
21
+ ToolSpec,
22
+ TurnEnd,
23
+ UserTurn,
24
+ )
25
+ from platybus.errors import AssistantError
26
+ from platybus_assistant.anthropic_provider import AnthropicProvider, AnthropicSettings
27
+ from platybus_assistant.openai_provider import (
28
+ OllamaSettings,
29
+ OpenAICompatibleProvider,
30
+ OpenAISettings,
31
+ )
32
+
33
+ TOOLS = (
34
+ ToolSpec(
35
+ "run_sql",
36
+ "Run SQL.",
37
+ {"type": "object", "properties": {"sql": {"type": "string"}}, "required": ["sql"]},
38
+ ),
39
+ )
40
+
41
+
42
+ @pytest.fixture
43
+ def server(monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]:
44
+ """A fake HTTP backend: ``state["respond"]`` builds the response, requests are recorded."""
45
+ state: dict[str, Any] = {"requests": [], "respond": None}
46
+
47
+ def handler(request: httpx2.Request) -> httpx2.Response:
48
+ state["requests"].append(request)
49
+ respond: Callable[[httpx2.Request], httpx2.Response] = state["respond"]
50
+ return respond(request)
51
+
52
+ monkeypatch.setattr(
53
+ http,
54
+ "HTTP_CLIENT_FACTORY",
55
+ lambda: httpx2.Client(transport=httpx2.MockTransport(handler)),
56
+ )
57
+ yield state
58
+
59
+
60
+ def sse(events: list[tuple[str | None, Any]]) -> httpx2.Response:
61
+ lines = []
62
+ for name, data in events:
63
+ if name:
64
+ lines.append(f"event: {name}")
65
+ lines.append(f"data: {data if isinstance(data, str) else json.dumps(data)}")
66
+ lines.append("")
67
+ return httpx2.Response(
68
+ 200, content="\n".join(lines).encode(), headers={"content-type": "text/event-stream"}
69
+ )
70
+
71
+
72
+ def request(model: str, turns: Any) -> ModelRequest:
73
+ return ModelRequest(model=model, system="SYSTEM", turns=turns, tools=TOOLS, max_tokens=1000)
74
+
75
+
76
+ # ---------------------------------------------------------------------- Anthropic
77
+ def anthropic_stream(stop_reason: str = "tool_use") -> httpx2.Response:
78
+ def block(index: int, block: dict[str, Any]) -> tuple[str, Any]:
79
+ return "content_block_start", {
80
+ "type": "content_block_start",
81
+ "index": index,
82
+ "content_block": block,
83
+ }
84
+
85
+ def delta(index: int, delta: dict[str, Any]) -> tuple[str, Any]:
86
+ return "content_block_delta", {
87
+ "type": "content_block_delta",
88
+ "index": index,
89
+ "delta": delta,
90
+ }
91
+
92
+ def stop(index: int) -> tuple[str, Any]:
93
+ return "content_block_stop", {"type": "content_block_stop", "index": index}
94
+
95
+ return sse(
96
+ [
97
+ (
98
+ "message_start",
99
+ {
100
+ "type": "message_start",
101
+ "message": {
102
+ "id": "msg_1",
103
+ "type": "message",
104
+ "role": "assistant",
105
+ "model": "claude-sonnet-5-5",
106
+ "content": [],
107
+ "stop_reason": None,
108
+ "stop_sequence": None,
109
+ "usage": {"input_tokens": 12, "output_tokens": 1},
110
+ },
111
+ },
112
+ ),
113
+ block(0, {"type": "text", "text": ""}),
114
+ delta(0, {"type": "text_delta", "text": "Let me "}),
115
+ delta(0, {"type": "text_delta", "text": "check."}),
116
+ stop(0),
117
+ block(1, {"type": "tool_use", "id": "toolu_1", "name": "run_sql", "input": {}}),
118
+ delta(1, {"type": "input_json_delta", "partial_json": '{"sql": "sel'}),
119
+ delta(1, {"type": "input_json_delta", "partial_json": 'ect 1"}'}),
120
+ stop(1),
121
+ (
122
+ "message_delta",
123
+ {
124
+ "type": "message_delta",
125
+ "delta": {"stop_reason": stop_reason, "stop_sequence": None},
126
+ "usage": {"output_tokens": 20},
127
+ },
128
+ ),
129
+ ("message_stop", {"type": "message_stop"}),
130
+ ]
131
+ )
132
+
133
+
134
+ def anthropic(settings: dict[str, Any] | None = None) -> AnthropicProvider:
135
+ return AnthropicProvider(
136
+ ProviderContext(
137
+ settings=AnthropicSettings.model_validate(
138
+ {"base_url": "https://api.test", **(settings or {})}
139
+ ),
140
+ environ={},
141
+ api_key="test-key",
142
+ )
143
+ )
144
+
145
+
146
+ def test_anthropic_streams_text_and_tool_calls(server: dict[str, Any]) -> None:
147
+ server["respond"] = lambda _: anthropic_stream()
148
+ provider = anthropic({"effort": "low"})
149
+ history = [
150
+ UserTurn("first question"),
151
+ AssistantTurn(
152
+ (
153
+ {"type": "text", "text": "old"},
154
+ {"type": "tool_call", "id": "t0", "name": "run_sql", "input": {"sql": "select 0"}},
155
+ ),
156
+ raw=[
157
+ {"type": "thinking", "thinking": "", "signature": "sig"},
158
+ {"type": "text", "text": "old"},
159
+ {"type": "tool_use", "id": "t0", "name": "run_sql", "input": {"sql": "select 0"}},
160
+ ],
161
+ raw_provider="anthropic",
162
+ ),
163
+ ToolResultsTurn((ToolResultContent("t0", "run_sql", "[[0]]", False),)),
164
+ UserTurn("next"),
165
+ ]
166
+ events = list(provider.stream(request("claude-sonnet-5-5", history)))
167
+ assert events[:2] == [TextDelta("Let me "), TextDelta("check.")]
168
+ assert events[2] == ToolCall("toolu_1", "run_sql", {"sql": "select 1"})
169
+ end = events[3]
170
+ assert isinstance(end, TurnEnd) and end.stop_reason == "tool_use"
171
+ assert end.usage is not None and end.usage.output_tokens == 20
172
+ assert end.raw == [
173
+ {"type": "text", "text": "Let me check."},
174
+ {"type": "tool_use", "id": "toolu_1", "name": "run_sql", "input": {"sql": "select 1"}},
175
+ ]
176
+
177
+ sent = server["requests"][0]
178
+ assert sent.url.path == "/v1/messages"
179
+ assert sent.headers["authorization"] == "Bearer test-key"
180
+ assert "server-side-fallback" in sent.headers.get("anthropic-beta", "")
181
+ body = json.loads(sent.content)
182
+ assert body["model"] == "claude-sonnet-5-5" and body["stream"] is True
183
+ assert body["fallbacks"] == "default"
184
+ assert body["system"] == [{"type": "text", "text": "SYSTEM"}]
185
+ assert body["tools"][0]["name"] == "run_sql"
186
+ assert body["output_config"] == {"effort": "low"}
187
+ assert body["cache_control"] == {"type": "ephemeral"}
188
+ roles = [m["role"] for m in body["messages"]]
189
+ assert roles == ["user", "assistant", "user"]
190
+ # Raw blocks (thinking signatures) are replayed unchanged; results then the new question.
191
+ assert body["messages"][1]["content"][0]["signature"] == "sig"
192
+ assert [b["type"] for b in body["messages"][2]["content"]] == ["tool_result", "text"]
193
+ assert body["messages"][2]["content"][0]["tool_use_id"] == "t0"
194
+
195
+
196
+ def test_anthropic_rebuilds_foreign_turns_and_skips_fallbacks(server: dict[str, Any]) -> None:
197
+ server["respond"] = lambda _: anthropic_stream("end_turn")
198
+ provider = anthropic({"refusal_fallback": False})
199
+ turns = [
200
+ UserTurn("q"),
201
+ AssistantTurn(
202
+ ({"type": "tool_call", "id": "call_9", "name": "run_sql", "input": {"sql": "x"}},),
203
+ raw=None,
204
+ raw_provider="openai",
205
+ ),
206
+ ToolResultsTurn((ToolResultContent("call_9", "run_sql", "boom", True),)),
207
+ ]
208
+ list(provider.stream(request("claude-haiku-5-5", turns)))
209
+ sent = server["requests"][0]
210
+ assert "anthropic-beta" not in sent.headers
211
+ body = json.loads(sent.content)
212
+ assert "fallbacks" not in body
213
+ assert body["messages"][1]["content"] == [
214
+ {"type": "tool_use", "id": "call_9", "name": "run_sql", "input": {"sql": "x"}}
215
+ ]
216
+ assert body["messages"][2]["content"][0]["is_error"] is True
217
+
218
+
219
+ def test_anthropic_errors_are_readable_and_keyless(server: dict[str, Any]) -> None:
220
+ server["respond"] = lambda _: httpx2.Response(
221
+ 401,
222
+ json={
223
+ "type": "error",
224
+ "error": {"type": "authentication_error", "message": "invalid x-api-key"},
225
+ },
226
+ )
227
+ with pytest.raises(AssistantError, match="authentication failed") as info:
228
+ list(anthropic().stream(request("claude-sonnet-5-5", [UserTurn("hi")])))
229
+ assert "test-key" not in info.value.message
230
+
231
+ server["respond"] = lambda _: httpx2.Response(
232
+ 400,
233
+ json={"type": "error", "error": {"type": "invalid_request_error", "message": "bad model"}},
234
+ )
235
+ with pytest.raises(AssistantError, match="400: bad model"):
236
+ list(anthropic().stream(request("nope", [UserTurn("hi")])))
237
+
238
+
239
+ # ---------------------------------------------------------------------- OpenAI-compatible
240
+ def chunk(
241
+ delta: dict[str, Any] | None = None, finish: str | None = None, usage: Any = None
242
+ ) -> dict[str, Any]:
243
+ choices = [] if delta is None else [{"index": 0, "delta": delta, "finish_reason": finish}]
244
+ data: dict[str, Any] = {
245
+ "id": "c1",
246
+ "object": "chat.completion.chunk",
247
+ "created": 1,
248
+ "model": "m",
249
+ "choices": choices,
250
+ }
251
+ if usage is not None:
252
+ data["usage"] = usage
253
+ return data
254
+
255
+
256
+ def openai_stream() -> httpx2.Response:
257
+ return sse(
258
+ [
259
+ (None, chunk({"role": "assistant", "content": "Look"})),
260
+ (None, chunk({"content": "ing."})),
261
+ (
262
+ None,
263
+ chunk(
264
+ {
265
+ "tool_calls": [
266
+ {
267
+ "index": 0,
268
+ "id": "call_1",
269
+ "type": "function",
270
+ "function": {"name": "run_sql", "arguments": '{"sql"'},
271
+ }
272
+ ]
273
+ }
274
+ ),
275
+ ),
276
+ (
277
+ None,
278
+ chunk({"tool_calls": [{"index": 0, "function": {"arguments": ': "select 1"}'}}]}),
279
+ ),
280
+ (None, chunk({}, finish="tool_calls")),
281
+ (
282
+ None,
283
+ chunk(None, usage={"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12}),
284
+ ),
285
+ (None, "[DONE]"),
286
+ ]
287
+ )
288
+
289
+
290
+ def test_openai_compatible_streams_tool_calls(server: dict[str, Any]) -> None:
291
+ server["respond"] = lambda _: openai_stream()
292
+ provider = OpenAICompatibleProvider(
293
+ ProviderContext(
294
+ settings=OpenAISettings.model_validate({"base_url": "http://127.0.0.1:8000/v1"}),
295
+ environ={},
296
+ api_key="test-key",
297
+ )
298
+ )
299
+ turns = [
300
+ UserTurn("q"),
301
+ AssistantTurn(
302
+ (
303
+ {"type": "text", "text": "a"},
304
+ {"type": "tool_call", "id": "t0", "name": "run_sql", "input": {"sql": "x"}},
305
+ ),
306
+ ),
307
+ ToolResultsTurn((ToolResultContent("t0", "run_sql", "boom", True),)),
308
+ UserTurn("again"),
309
+ ]
310
+ events = list(provider.stream(request("my-model", turns)))
311
+ assert events[:2] == [TextDelta("Look"), TextDelta("ing.")]
312
+ assert events[2] == ToolCall("call_1", "run_sql", {"sql": "select 1"})
313
+ end = events[3]
314
+ assert isinstance(end, TurnEnd) and end.stop_reason == "tool_use"
315
+ assert end.usage is not None and (end.usage.input_tokens, end.usage.output_tokens) == (5, 7)
316
+
317
+ sent = server["requests"][0]
318
+ assert str(sent.url) == "http://127.0.0.1:8000/v1/chat/completions"
319
+ assert sent.headers["authorization"] == "Bearer test-key"
320
+ body = json.loads(sent.content)
321
+ assert body["stream"] is True and body["max_completion_tokens"] == 1000
322
+ assert body["stream_options"] == {"include_usage": True}
323
+ assert body["tools"][0]["function"]["name"] == "run_sql"
324
+ roles = [m["role"] for m in body["messages"]]
325
+ assert roles == ["system", "user", "assistant", "tool", "user"]
326
+ assert body["messages"][2]["tool_calls"][0]["function"]["arguments"] == '{"sql": "x"}'
327
+ assert body["messages"][3] == {"role": "tool", "tool_call_id": "t0", "content": "ERROR: boom"}
328
+
329
+
330
+ def test_ollama_preset(server: dict[str, Any]) -> None:
331
+ server["respond"] = lambda _: sse(
332
+ [(None, chunk({"content": "hi"})), (None, chunk({}, finish="stop")), (None, "[DONE]")]
333
+ )
334
+ provider = OpenAICompatibleProvider(
335
+ ProviderContext(settings=OllamaSettings.model_validate({}), environ={}),
336
+ key="ollama",
337
+ title="Ollama",
338
+ )
339
+ events = list(provider.stream(request("qwen3", [UserTurn("hi")])))
340
+ assert events == [TextDelta("hi"), TurnEnd("end_turn", None)]
341
+ sent = server["requests"][0]
342
+ assert str(sent.url) == "http://127.0.0.1:11434/v1/chat/completions"
343
+ body = json.loads(sent.content)
344
+ assert body["max_tokens"] == 1000 and "stream_options" not in body
345
+
346
+
347
+ def test_openai_errors(server: dict[str, Any]) -> None:
348
+ server["respond"] = lambda _: httpx2.Response(429, json={"error": {"message": "slow down"}})
349
+ provider = OpenAICompatibleProvider(
350
+ ProviderContext(
351
+ settings=OpenAISettings.model_validate({"base_url": "http://127.0.0.1:1/v1"}),
352
+ environ={},
353
+ api_key="k",
354
+ )
355
+ )
356
+ provider.client = provider.client.with_options(max_retries=0)
357
+ with pytest.raises(AssistantError, match="rate limited"):
358
+ list(provider.stream(request("m", [UserTurn("hi")])))