polyllm-anthropic 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PolyLLM contributors
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,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyllm-anthropic
3
+ Version: 0.1.0
4
+ Summary: Anthropic plugin for PolyLLM.
5
+ Author: PolyLLM contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://polyllm.raingpt.top
8
+ Project-URL: Repository, https://github.com/you-want/PolyLLM
9
+ Project-URL: Issues, https://github.com/you-want/PolyLLM/issues
10
+ Keywords: llm,polyllm,anthropic,claude
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: polyllm-core>=0.1.0
25
+ Dynamic: license-file
26
+
27
+ # PolyLLM Anthropic Plugin for Python
28
+
29
+ ```python
30
+ from polyllm_core import create_llm
31
+ from polyllm_anthropic import AnthropicPlugin
32
+
33
+ llm = create_llm(plugins=[AnthropicPlugin()], providers={"anthropic": {"api_key": "..."}})
34
+ response = await llm.chat("anthropic:claude-haiku-4-5", messages=[{"role": "user", "content": "你好"}])
35
+ ```
@@ -0,0 +1,9 @@
1
+ # PolyLLM Anthropic Plugin for Python
2
+
3
+ ```python
4
+ from polyllm_core import create_llm
5
+ from polyllm_anthropic import AnthropicPlugin
6
+
7
+ llm = create_llm(plugins=[AnthropicPlugin()], providers={"anthropic": {"api_key": "..."}})
8
+ response = await llm.chat("anthropic:claude-haiku-4-5", messages=[{"role": "user", "content": "你好"}])
9
+ ```
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "polyllm-anthropic"
7
+ version = "0.1.0"
8
+ description = "Anthropic plugin for PolyLLM."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["polyllm-core>=0.1.0"]
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ authors = [{ name = "PolyLLM contributors" }]
15
+ keywords = ["llm", "polyllm", "anthropic", "claude"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://polyllm.raingpt.top"
31
+ Repository = "https://github.com/you-want/PolyLLM"
32
+ Issues = "https://github.com/you-want/PolyLLM/issues"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.setuptools.package-data]
38
+ polyllm_anthropic = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from .plugin import AnthropicPlugin, parse_sse
2
+ from .specs import models
3
+
4
+ __all__ = ["AnthropicPlugin", "models", "parse_sse"]
@@ -0,0 +1,235 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from typing import Any, AsyncIterator, Callable, cast
6
+ from urllib.error import HTTPError
7
+ from urllib.request import Request, urlopen
8
+
9
+ from polyllm_core.config import resolve_provider_runtime
10
+ from polyllm_core.errors import PolyLLMError
11
+ from polyllm_core.types import (
12
+ ChatContext,
13
+ FinishReason,
14
+ LLMPlugin,
15
+ ModelSpec,
16
+ ProviderConfig,
17
+ ProviderModelInfo,
18
+ UnifiedChoice,
19
+ UnifiedMessage,
20
+ UnifiedRequest,
21
+ UnifiedResponse,
22
+ UnifiedStreamChunk,
23
+ UnifiedToolCall,
24
+ UnifiedUsage,
25
+ )
26
+
27
+ from .specs import capabilities, models
28
+
29
+ Transport = Callable[[str, str, dict[str, str], dict[str, Any] | None, int], tuple[int, str]]
30
+
31
+
32
+ class AnthropicPlugin(LLMPlugin):
33
+ provider = "anthropic"
34
+ models = models
35
+
36
+ def __init__(self, transport: Transport | None = None):
37
+ self._transport = transport or urllib_transport
38
+
39
+ async def chat(
40
+ self,
41
+ request: UnifiedRequest,
42
+ config: ProviderConfig,
43
+ context: ChatContext,
44
+ ) -> UnifiedResponse:
45
+ status, body = await self._request("POST", "/v1/messages", self._build_body(request), config, context)
46
+ data = self._parse_json(status, body)
47
+ content = data.get("content", [])
48
+ text = "".join(part.get("text", "") for part in content if part.get("type") == "text")
49
+ tool_calls = tuple(
50
+ UnifiedToolCall(
51
+ id=part["id"],
52
+ type="function",
53
+ function={"name": part["name"], "arguments": json.dumps(part.get("input", {}), ensure_ascii=False)},
54
+ )
55
+ for part in content
56
+ if part.get("type") == "tool_use"
57
+ )
58
+ finish_reason: FinishReason = (
59
+ "tool_calls" if tool_calls else cast(FinishReason, data.get("stop_reason", "other"))
60
+ )
61
+ usage = data.get("usage", {})
62
+ return UnifiedResponse(
63
+ id=data["id"],
64
+ model=data["model"],
65
+ choices=[
66
+ UnifiedChoice(
67
+ index=0,
68
+ message=UnifiedMessage(role="assistant", content=text, tool_calls=tool_calls),
69
+ finish_reason=finish_reason,
70
+ )
71
+ ],
72
+ usage=UnifiedUsage(
73
+ prompt_tokens=usage.get("input_tokens", 0),
74
+ completion_tokens=usage.get("output_tokens", 0),
75
+ total_tokens=usage.get("input_tokens", 0) + usage.get("output_tokens", 0),
76
+ ),
77
+ provider_metadata=data.get("metadata"),
78
+ )
79
+
80
+ async def chat_stream(
81
+ self,
82
+ request: UnifiedRequest,
83
+ config: ProviderConfig,
84
+ context: ChatContext,
85
+ ) -> AsyncIterator[UnifiedStreamChunk]:
86
+ body = self._build_body(request)
87
+ body["stream"] = True
88
+ status, text = await self._request("POST", "/v1/messages", body, config, context)
89
+ response_id = "anthropic-stream"
90
+ model = request.model
91
+ if status < 200 or status >= 300:
92
+ raise PolyLLMError("PROVIDER_ERROR", f"Anthropic API 错误: {status} {text}", {"status": status})
93
+ for event in parse_sse(text):
94
+ event_type = event.get("type")
95
+ if event_type == "content_block_delta":
96
+ delta = event.get("delta", {})
97
+ yield UnifiedStreamChunk(id=response_id, model=model, delta={"content": delta.get("text", "")})
98
+ elif event_type == "message_delta":
99
+ yield UnifiedStreamChunk(
100
+ id=response_id,
101
+ model=model,
102
+ delta={},
103
+ finish_reason=cast(
104
+ FinishReason,
105
+ event.get("delta", {}).get("stop_reason", "other"),
106
+ ),
107
+ )
108
+
109
+ async def list_models(self, config: ProviderConfig) -> list[ProviderModelInfo]:
110
+ status, body = await self._request("GET", "/v1/models", None, config, None)
111
+ data = self._parse_json(status, body)
112
+ return [
113
+ ProviderModelInfo(
114
+ id=item["id"],
115
+ display_name=item.get("display_name"),
116
+ metadata=item.get("metadata"),
117
+ )
118
+ for item in data.get("data", [])
119
+ ]
120
+
121
+ def create_model_spec(self, model_id: str) -> ModelSpec:
122
+ return ModelSpec(
123
+ id=model_id,
124
+ provider=self.provider,
125
+ capabilities=capabilities,
126
+ context_window=200000,
127
+ max_output=8192,
128
+ )
129
+
130
+ def _build_body(self, request: UnifiedRequest) -> dict[str, Any]:
131
+ system_parts = [message.content for message in request.messages if message.role == "system"]
132
+ messages = [
133
+ {
134
+ "role": message.role,
135
+ "content": message.content,
136
+ **({"tool_call_id": message.tool_call_id} if message.tool_call_id else {}),
137
+ **(
138
+ {
139
+ "tool_calls": [
140
+ {
141
+ "id": call.id,
142
+ "type": "function",
143
+ "function": dict(call.function),
144
+ }
145
+ for call in message.tool_calls
146
+ ]
147
+ }
148
+ if message.tool_calls
149
+ else {}
150
+ ),
151
+ }
152
+ for message in request.messages
153
+ if message.role in ("user", "assistant", "tool")
154
+ ]
155
+ body: dict[str, Any] = {
156
+ "model": request.model,
157
+ "messages": messages,
158
+ "max_tokens": request.max_tokens or 4096,
159
+ }
160
+ if system_parts:
161
+ body["system"] = "\n".join(part for part in system_parts if isinstance(part, str))
162
+ if request.temperature is not None:
163
+ body["temperature"] = request.temperature
164
+ if request.top_p is not None:
165
+ body["top_p"] = request.top_p
166
+ if request.tools:
167
+ body["tools"] = [
168
+ {
169
+ "name": tool.function["name"],
170
+ "description": tool.function.get("description", ""),
171
+ "input_schema": tool.function.get("parameters", {"type": "object"}),
172
+ }
173
+ for tool in request.tools
174
+ ]
175
+ return body
176
+
177
+ async def _request(
178
+ self,
179
+ method: str,
180
+ path: str,
181
+ payload: dict[str, Any] | None,
182
+ config: ProviderConfig,
183
+ context: ChatContext | None,
184
+ ) -> tuple[int, str]:
185
+ runtime = resolve_provider_runtime(self.provider, config)
186
+ base_url = (runtime.base_url or "https://api.anthropic.com").rstrip("/")
187
+ headers = {
188
+ "x-api-key": runtime.api_key,
189
+ "anthropic-version": "2023-06-01",
190
+ **runtime.headers,
191
+ }
192
+ if payload is not None:
193
+ headers["Content-Type"] = "application/json"
194
+ timeout_ms = context.timeout_ms if context is not None and context.timeout_ms is not None else 120000
195
+ return await asyncio.to_thread(
196
+ self._transport, method, f"{base_url}{path}", headers, payload, timeout_ms
197
+ )
198
+
199
+ @staticmethod
200
+ def _parse_json(status: int, body: str) -> dict[str, Any]:
201
+ try:
202
+ data = cast(dict[str, Any], json.loads(body))
203
+ except json.JSONDecodeError as error:
204
+ raise PolyLLMError("PROVIDER_ERROR", f"Anthropic 返回无效 JSON: {body[:200]}", {"status": status}) from error
205
+ if status < 200 or status >= 300:
206
+ raise PolyLLMError("PROVIDER_ERROR", f"Anthropic API 错误: {status} {body}", {"status": status, "body": data})
207
+ return data
208
+
209
+
210
+ def urllib_transport(
211
+ method: str,
212
+ url: str,
213
+ headers: dict[str, str],
214
+ payload: dict[str, Any] | None,
215
+ timeout_ms: int,
216
+ ) -> tuple[int, str]:
217
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
218
+ request = Request(url, data=data, headers=headers, method=method)
219
+ try:
220
+ with urlopen(request, timeout=timeout_ms / 1000) as response:
221
+ return response.status, response.read().decode("utf-8")
222
+ except HTTPError as error:
223
+ return error.code, error.read().decode("utf-8")
224
+
225
+
226
+ def parse_sse(text: str) -> list[dict[str, Any]]:
227
+ events: list[dict[str, Any]] = []
228
+ for line in text.splitlines():
229
+ if not line.startswith("data:"):
230
+ continue
231
+ value = line.removeprefix("data:").strip()
232
+ if not value:
233
+ continue
234
+ events.append(cast(dict[str, Any], json.loads(value)))
235
+ return events
File without changes
@@ -0,0 +1,43 @@
1
+ from polyllm_core.types import ModelCapabilities, ModelSpec, NumericParamRange
2
+
3
+ capabilities = ModelCapabilities(
4
+ streaming=True,
5
+ vision=True,
6
+ function_calling=True,
7
+ json_mode=False,
8
+ system_prompt=True,
9
+ )
10
+
11
+ models = (
12
+ ModelSpec(
13
+ id="claude-sonnet-4-5",
14
+ provider="anthropic",
15
+ aliases=("claude-sonnet", "sonnet"),
16
+ version="2025-09-29",
17
+ snapshot="claude-sonnet-4-5-20250929",
18
+ is_latest=True,
19
+ capabilities=capabilities,
20
+ params={
21
+ "temperature": NumericParamRange(0, 1, 1),
22
+ "max_tokens": NumericParamRange(1, 8192, 4096, field="max_tokens"),
23
+ "top_p": NumericParamRange(0, 1, 1),
24
+ },
25
+ context_window=200000,
26
+ max_output=8192,
27
+ ),
28
+ ModelSpec(
29
+ id="claude-haiku-4-5",
30
+ provider="anthropic",
31
+ aliases=("claude-haiku", "haiku"),
32
+ version="2025-10-01",
33
+ snapshot="claude-haiku-4-5-20251001",
34
+ capabilities=capabilities,
35
+ params={
36
+ "temperature": NumericParamRange(0, 1, 1),
37
+ "max_tokens": NumericParamRange(1, 8192, 4096, field="max_tokens"),
38
+ "top_p": NumericParamRange(0, 1, 1),
39
+ },
40
+ context_window=200000,
41
+ max_output=8192,
42
+ ),
43
+ )
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyllm-anthropic
3
+ Version: 0.1.0
4
+ Summary: Anthropic plugin for PolyLLM.
5
+ Author: PolyLLM contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://polyllm.raingpt.top
8
+ Project-URL: Repository, https://github.com/you-want/PolyLLM
9
+ Project-URL: Issues, https://github.com/you-want/PolyLLM/issues
10
+ Keywords: llm,polyllm,anthropic,claude
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: polyllm-core>=0.1.0
25
+ Dynamic: license-file
26
+
27
+ # PolyLLM Anthropic Plugin for Python
28
+
29
+ ```python
30
+ from polyllm_core import create_llm
31
+ from polyllm_anthropic import AnthropicPlugin
32
+
33
+ llm = create_llm(plugins=[AnthropicPlugin()], providers={"anthropic": {"api_key": "..."}})
34
+ response = await llm.chat("anthropic:claude-haiku-4-5", messages=[{"role": "user", "content": "你好"}])
35
+ ```
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/polyllm_anthropic/__init__.py
5
+ src/polyllm_anthropic/plugin.py
6
+ src/polyllm_anthropic/py.typed
7
+ src/polyllm_anthropic/specs.py
8
+ src/polyllm_anthropic.egg-info/PKG-INFO
9
+ src/polyllm_anthropic.egg-info/SOURCES.txt
10
+ src/polyllm_anthropic.egg-info/dependency_links.txt
11
+ src/polyllm_anthropic.egg-info/requires.txt
12
+ src/polyllm_anthropic.egg-info/top_level.txt
13
+ tests/test_anthropic.py
14
+ tests/test_stream.py
@@ -0,0 +1 @@
1
+ polyllm-core>=0.1.0
@@ -0,0 +1 @@
1
+ polyllm_anthropic
@@ -0,0 +1,58 @@
1
+ import asyncio
2
+ import json
3
+ import unittest
4
+
5
+ from polyllm_core.types import ProviderConfig, UnifiedMessage, UnifiedRequest
6
+ from polyllm_anthropic import AnthropicPlugin
7
+ from polyllm_core import ModelRegistry
8
+
9
+
10
+ class AnthropicTests(unittest.TestCase):
11
+ def test_registry_aliases_and_snapshots(self):
12
+ registry = ModelRegistry()
13
+ for spec in AnthropicPlugin.models:
14
+ registry.register(spec)
15
+ self.assertEqual(registry.resolve("anthropic:sonnet").id, "claude-sonnet-4-5")
16
+ self.assertEqual(registry.resolve("anthropic:haiku").id, "claude-haiku-4-5")
17
+ self.assertEqual(
18
+ registry.resolve("anthropic:claude-sonnet-4-5-20250929").id,
19
+ "claude-sonnet-4-5",
20
+ )
21
+
22
+ def test_chat_wire_and_response(self):
23
+ calls = []
24
+
25
+ def transport(method, url, headers, payload, timeout):
26
+ calls.append((method, url, headers, payload))
27
+ return 200, json.dumps(
28
+ {
29
+ "id": "msg",
30
+ "model": "claude-haiku-4-5",
31
+ "content": [{"type": "text", "text": "ok"}],
32
+ "stop_reason": "end_turn",
33
+ "usage": {"input_tokens": 2, "output_tokens": 3},
34
+ }
35
+ )
36
+
37
+ response = asyncio.run(
38
+ AnthropicPlugin(transport).chat(
39
+ UnifiedRequest(
40
+ model="claude-haiku-4-5",
41
+ messages=[
42
+ UnifiedMessage(role="system", content="be brief"),
43
+ UnifiedMessage(role="user", content="hi"),
44
+ ],
45
+ max_tokens=128,
46
+ ),
47
+ ProviderConfig(api_key="k"),
48
+ None,
49
+ )
50
+ )
51
+ self.assertEqual(response.choices[0].message.content, "ok")
52
+ self.assertEqual(response.usage.total_tokens, 5)
53
+ self.assertEqual(calls[0][3]["system"], "be brief")
54
+ self.assertEqual(calls[0][2]["anthropic-version"], "2023-06-01")
55
+
56
+
57
+ if __name__ == "__main__":
58
+ unittest.main()
@@ -0,0 +1,33 @@
1
+ import asyncio
2
+ import unittest
3
+
4
+ from polyllm_anthropic import AnthropicPlugin
5
+ from polyllm_core.types import ProviderConfig, UnifiedMessage, UnifiedRequest
6
+
7
+
8
+ class AnthropicStreamTests(unittest.TestCase):
9
+ def test_stream_parses_sse(self):
10
+ sse = (
11
+ 'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"he"}}\n\n'
12
+ 'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"llo"}}\n\n'
13
+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'
14
+ )
15
+
16
+ async def run():
17
+ chunks = []
18
+ plugin = AnthropicPlugin(lambda *args: (200, sse))
19
+ async for chunk in plugin.chat_stream(
20
+ UnifiedRequest(model="claude-haiku-4-5", messages=[UnifiedMessage(role="user", content="hi")]),
21
+ ProviderConfig(api_key="k"),
22
+ None,
23
+ ):
24
+ chunks.append(chunk)
25
+ return chunks
26
+
27
+ chunks = asyncio.run(run())
28
+ self.assertEqual([chunk.delta.get("content") for chunk in chunks], ["he", "llo", None])
29
+ self.assertEqual(chunks[-1].finish_reason, "end_turn")
30
+
31
+
32
+ if __name__ == "__main__":
33
+ unittest.main()