polyllm-openai-compatible 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,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyllm-openai-compatible
3
+ Version: 0.1.0
4
+ Summary: OpenAI-compatible endpoint 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,openai-compatible,gateway
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 OpenAI-Compatible Plugin for Python
28
+
29
+ 适用于 Qwen、Moonshot、OpenRouter、Groq、vLLM、Ollama 等所有兼容 OpenAI Chat Completions 协议的服务。
30
+
31
+ ```python
32
+ from polyllm_core import create_llm
33
+ from polyllm_openai_compatible import OpenAICompatiblePlugin
34
+
35
+ plugin = OpenAICompatiblePlugin()
36
+ llm = create_llm(
37
+ plugins=[plugin],
38
+ providers={"openai-compatible": {"api_key": "...", "base_url": "https://your-endpoint/v1"}},
39
+ allow_unlisted_models=True,
40
+ )
41
+ response = await llm.chat("openai-compatible:your-model", messages=[{"role": "user", "content": "你好"}])
42
+ ```
@@ -0,0 +1,16 @@
1
+ # PolyLLM OpenAI-Compatible Plugin for Python
2
+
3
+ 适用于 Qwen、Moonshot、OpenRouter、Groq、vLLM、Ollama 等所有兼容 OpenAI Chat Completions 协议的服务。
4
+
5
+ ```python
6
+ from polyllm_core import create_llm
7
+ from polyllm_openai_compatible import OpenAICompatiblePlugin
8
+
9
+ plugin = OpenAICompatiblePlugin()
10
+ llm = create_llm(
11
+ plugins=[plugin],
12
+ providers={"openai-compatible": {"api_key": "...", "base_url": "https://your-endpoint/v1"}},
13
+ allow_unlisted_models=True,
14
+ )
15
+ response = await llm.chat("openai-compatible:your-model", messages=[{"role": "user", "content": "你好"}])
16
+ ```
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "polyllm-openai-compatible"
7
+ version = "0.1.0"
8
+ description = "OpenAI-compatible endpoint 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", "openai-compatible", "gateway"]
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_openai_compatible = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from .plugin import OpenAICompatiblePlugin, parse_sse, urllib_transport
2
+
3
+ __all__ = ["OpenAICompatiblePlugin", "parse_sse", "urllib_transport"]
@@ -0,0 +1,227 @@
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
+ LLMPlugin,
14
+ ModelCapabilities,
15
+ ModelSpec,
16
+ ProviderConfig,
17
+ ProviderModelInfo,
18
+ UnifiedChoice,
19
+ UnifiedMessage,
20
+ UnifiedRequest,
21
+ UnifiedResponse,
22
+ UnifiedStreamChunk,
23
+ UnifiedToolCall,
24
+ UnifiedUsage,
25
+ )
26
+
27
+ Transport = Callable[[str, str, dict[str, str], dict[str, Any] | None, int], tuple[int, str]]
28
+
29
+
30
+ class OpenAICompatiblePlugin(LLMPlugin):
31
+ provider = "openai-compatible"
32
+ models: tuple[ModelSpec, ...] = ()
33
+
34
+ def __init__(self, transport: Transport | None = None, provider: str = "openai-compatible"):
35
+ self.provider = provider
36
+ self._transport = transport or urllib_transport
37
+
38
+ async def chat(
39
+ self,
40
+ request: UnifiedRequest,
41
+ config: ProviderConfig,
42
+ context: ChatContext,
43
+ ) -> UnifiedResponse:
44
+ status, body = await self._request("POST", "/chat/completions", self._build_body(request), config, context)
45
+ data = self._parse_json(status, body)
46
+ choice = data["choices"][0]
47
+ message = choice["message"]
48
+ return UnifiedResponse(
49
+ id=data["id"],
50
+ model=data["model"],
51
+ choices=[
52
+ UnifiedChoice(
53
+ index=choice["index"],
54
+ message=UnifiedMessage(
55
+ role="assistant",
56
+ content=message.get("content") or "",
57
+ tool_calls=tuple(
58
+ UnifiedToolCall(
59
+ id=call["id"],
60
+ type="function",
61
+ function=dict(call["function"]),
62
+ )
63
+ for call in message.get("tool_calls", [])
64
+ ),
65
+ ),
66
+ finish_reason=choice.get("finish_reason", "other"),
67
+ )
68
+ ],
69
+ usage=self._parse_usage(data.get("usage", {})),
70
+ provider_metadata=data.get("metadata"),
71
+ )
72
+
73
+ async def chat_stream(
74
+ self,
75
+ request: UnifiedRequest,
76
+ config: ProviderConfig,
77
+ context: ChatContext,
78
+ ) -> AsyncIterator[UnifiedStreamChunk]:
79
+ body = self._build_body(request)
80
+ body["stream"] = True
81
+ status, text = await self._request("POST", "/chat/completions", body, config, context)
82
+ if status < 200 or status >= 300:
83
+ raise PolyLLMError(
84
+ "PROVIDER_ERROR",
85
+ f"OpenAI-compatible API 错误: {status} {text}",
86
+ {"status": status},
87
+ )
88
+ for event in parse_sse(text):
89
+ yield UnifiedStreamChunk(
90
+ id=event["id"],
91
+ model=event["model"],
92
+ delta=dict(event.get("delta", {})),
93
+ finish_reason=event.get("finish_reason"),
94
+ )
95
+
96
+ async def list_models(self, config: ProviderConfig) -> list[ProviderModelInfo]:
97
+ status, body = await self._request("GET", "/models", None, config, None)
98
+ data = self._parse_json(status, body)
99
+ return [
100
+ ProviderModelInfo(
101
+ id=item["id"],
102
+ display_name=item.get("display_name") or item.get("name"),
103
+ owned_by=item.get("owned_by"),
104
+ created_at=item.get("created"),
105
+ metadata=item.get("metadata"),
106
+ )
107
+ for item in data.get("data", [])
108
+ ]
109
+
110
+ def create_model_spec(self, model_id: str) -> ModelSpec:
111
+ return ModelSpec(
112
+ id=model_id,
113
+ provider=self.provider,
114
+ capabilities=ModelCapabilities(
115
+ streaming=True,
116
+ vision=True,
117
+ function_calling=True,
118
+ json_mode=True,
119
+ system_prompt=True,
120
+ ),
121
+ context_window=128000,
122
+ max_output=16384,
123
+ )
124
+
125
+ def _build_body(self, request: UnifiedRequest) -> dict[str, Any]:
126
+ body: dict[str, Any] = {
127
+ "model": request.model,
128
+ "messages": [
129
+ {
130
+ "role": message.role,
131
+ "content": message.content,
132
+ **({"name": message.name} if message.name else {}),
133
+ **({"tool_call_id": message.tool_call_id} if message.tool_call_id else {}),
134
+ **(
135
+ {"tool_calls": [dict(call.__dict__) for call in message.tool_calls]}
136
+ if message.tool_calls
137
+ else {}
138
+ ),
139
+ }
140
+ for message in request.messages
141
+ ],
142
+ }
143
+ if request.temperature is not None:
144
+ body["temperature"] = request.temperature
145
+ if request.max_tokens is not None:
146
+ body["max_tokens"] = request.max_tokens
147
+ if request.top_p is not None:
148
+ body["top_p"] = request.top_p
149
+ if request.json_mode:
150
+ body["response_format"] = {"type": "json_object"}
151
+ if request.tools:
152
+ body["tools"] = [{"type": "function", "function": dict(tool.function)} for tool in request.tools]
153
+ return body
154
+
155
+ async def _request(
156
+ self,
157
+ method: str,
158
+ path: str,
159
+ payload: dict[str, Any] | None,
160
+ config: ProviderConfig,
161
+ context: ChatContext | None,
162
+ ) -> tuple[int, str]:
163
+ runtime = resolve_provider_runtime(self.provider, config)
164
+ if not runtime.base_url:
165
+ raise PolyLLMError(
166
+ "INVALID_CONFIG",
167
+ "OpenAI-compatible 供应商必须配置 providers[].base_url",
168
+ {"provider": self.provider},
169
+ )
170
+ base_url = runtime.base_url.rstrip("/")
171
+ headers = {"Authorization": f"Bearer {runtime.api_key}", **runtime.headers}
172
+ if payload is not None:
173
+ headers["Content-Type"] = "application/json"
174
+ timeout_ms = context.timeout_ms if context is not None and context.timeout_ms is not None else 120000
175
+ return await asyncio.to_thread(
176
+ self._transport, method, f"{base_url}{path}", headers, payload, timeout_ms
177
+ )
178
+
179
+ @staticmethod
180
+ def _parse_usage(data: dict[str, Any]) -> UnifiedUsage:
181
+ return UnifiedUsage(
182
+ prompt_tokens=data.get("prompt_tokens", 0),
183
+ completion_tokens=data.get("completion_tokens", 0),
184
+ total_tokens=data.get("total_tokens", 0),
185
+ )
186
+
187
+ @staticmethod
188
+ def _parse_json(status: int, body: str) -> dict[str, Any]:
189
+ try:
190
+ data = cast(dict[str, Any], json.loads(body))
191
+ except json.JSONDecodeError as error:
192
+ raise PolyLLMError("PROVIDER_ERROR", f"服务返回无效 JSON: {body[:200]}", {"status": status}) from error
193
+ if status < 200 or status >= 300:
194
+ raise PolyLLMError(
195
+ "PROVIDER_ERROR",
196
+ f"OpenAI-compatible API 错误: {status} {body}",
197
+ {"status": status, "body": data},
198
+ )
199
+ return data
200
+
201
+
202
+ def urllib_transport(
203
+ method: str,
204
+ url: str,
205
+ headers: dict[str, str],
206
+ payload: dict[str, Any] | None,
207
+ timeout_ms: int,
208
+ ) -> tuple[int, str]:
209
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
210
+ request = Request(url, data=data, headers=headers, method=method)
211
+ try:
212
+ with urlopen(request, timeout=timeout_ms / 1000) as response:
213
+ return response.status, response.read().decode("utf-8")
214
+ except HTTPError as error:
215
+ return error.code, error.read().decode("utf-8")
216
+
217
+
218
+ def parse_sse(text: str) -> list[dict[str, Any]]:
219
+ events: list[dict[str, Any]] = []
220
+ for line in text.splitlines():
221
+ if not line.startswith("data:"):
222
+ continue
223
+ value = line.removeprefix("data:").strip()
224
+ if not value or value == "[DONE]":
225
+ continue
226
+ events.append(json.loads(value))
227
+ return events
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyllm-openai-compatible
3
+ Version: 0.1.0
4
+ Summary: OpenAI-compatible endpoint 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,openai-compatible,gateway
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 OpenAI-Compatible Plugin for Python
28
+
29
+ 适用于 Qwen、Moonshot、OpenRouter、Groq、vLLM、Ollama 等所有兼容 OpenAI Chat Completions 协议的服务。
30
+
31
+ ```python
32
+ from polyllm_core import create_llm
33
+ from polyllm_openai_compatible import OpenAICompatiblePlugin
34
+
35
+ plugin = OpenAICompatiblePlugin()
36
+ llm = create_llm(
37
+ plugins=[plugin],
38
+ providers={"openai-compatible": {"api_key": "...", "base_url": "https://your-endpoint/v1"}},
39
+ allow_unlisted_models=True,
40
+ )
41
+ response = await llm.chat("openai-compatible:your-model", messages=[{"role": "user", "content": "你好"}])
42
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/polyllm_openai_compatible/__init__.py
5
+ src/polyllm_openai_compatible/plugin.py
6
+ src/polyllm_openai_compatible/py.typed
7
+ src/polyllm_openai_compatible.egg-info/PKG-INFO
8
+ src/polyllm_openai_compatible.egg-info/SOURCES.txt
9
+ src/polyllm_openai_compatible.egg-info/dependency_links.txt
10
+ src/polyllm_openai_compatible.egg-info/requires.txt
11
+ src/polyllm_openai_compatible.egg-info/top_level.txt
12
+ tests/test_openai_compatible.py
@@ -0,0 +1,47 @@
1
+ import asyncio
2
+ import json
3
+ import unittest
4
+
5
+ from polyllm_core.types import ProviderConfig, UnifiedMessage, UnifiedRequest
6
+ from polyllm_openai_compatible import OpenAICompatiblePlugin
7
+
8
+
9
+ class OpenAICompatibleTests(unittest.TestCase):
10
+ def test_requires_base_url(self):
11
+ plugin = OpenAICompatiblePlugin()
12
+ with self.assertRaises(Exception):
13
+ asyncio.run(plugin.chat(UnifiedRequest(model="m", messages=[]), ProviderConfig(api_key="k"), None))
14
+
15
+ def test_chat_uses_provider_base_url(self):
16
+ urls = []
17
+
18
+ def transport(method, url, headers, payload, timeout):
19
+ urls.append(url)
20
+ return 200, json.dumps(
21
+ {
22
+ "id": "r",
23
+ "model": "m",
24
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
25
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
26
+ }
27
+ )
28
+
29
+ response = asyncio.run(
30
+ OpenAICompatiblePlugin(transport).chat(
31
+ UnifiedRequest(model="m", messages=[UnifiedMessage(role="user", content="hi")]),
32
+ ProviderConfig(api_key="k", base_url="https://example.com/v1/"),
33
+ None,
34
+ )
35
+ )
36
+ self.assertEqual(response.model, "m")
37
+ self.assertEqual(urls[0], "https://example.com/v1/chat/completions")
38
+
39
+ def test_dynamic_model(self):
40
+ plugin = OpenAICompatiblePlugin()
41
+ spec = plugin.create_model_spec("qwen-max")
42
+ self.assertEqual(spec.provider, "openai-compatible")
43
+ self.assertEqual(spec.id, "qwen-max")
44
+
45
+
46
+ if __name__ == "__main__":
47
+ unittest.main()