polyllm-ollama 0.3.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-ollama
3
+ Version: 0.3.0
4
+ Summary: Ollama (local OpenAI-compatible) 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,ollama
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.3.0
25
+ Dynamic: license-file
26
+
27
+ # PolyLLM OpenAI Plugin for Python
28
+
29
+ ```python
30
+ from polyllm_core import create_llm
31
+ from polyllm_openai import OpenAIPlugin
32
+
33
+ llm = create_llm(plugins=[OpenAIPlugin()], providers={"openai": {"api_key": "..."}})
34
+ response = await llm.chat("openai:gpt-4o-mini", messages=[{"role": "user", "content": "你好"}])
35
+ ```
@@ -0,0 +1,9 @@
1
+ # PolyLLM OpenAI Plugin for Python
2
+
3
+ ```python
4
+ from polyllm_core import create_llm
5
+ from polyllm_openai import OpenAIPlugin
6
+
7
+ llm = create_llm(plugins=[OpenAIPlugin()], providers={"openai": {"api_key": "..."}})
8
+ response = await llm.chat("openai:gpt-4o-mini", 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-ollama"
7
+ version = "0.3.0"
8
+ description = "Ollama (local OpenAI-compatible) plugin for PolyLLM."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["polyllm-core>=0.3.0"]
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ authors = [{ name = "PolyLLM contributors" }]
15
+ keywords = ["llm", "polyllm", "ollama"]
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_ollama = ["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 OllamaPlugin
2
+ from .specs import models
3
+
4
+ __all__ = ["OllamaPlugin", "models"]
@@ -0,0 +1,225 @@
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.errors import PolyLLMError
10
+ from polyllm_core.types import (
11
+ ChatContext,
12
+ LLMPlugin,
13
+ ModelCapabilities,
14
+ ModelSpec,
15
+ ProviderConfig,
16
+ ProviderModelInfo,
17
+ UnifiedChoice,
18
+ UnifiedMessage,
19
+ UnifiedRequest,
20
+ UnifiedResponse,
21
+ UnifiedStreamChunk,
22
+ UnifiedToolCall,
23
+ UnifiedUsage,
24
+ )
25
+
26
+ from .specs import models
27
+
28
+ Transport = Callable[[str, str, dict[str, str], dict[str, Any] | None, int], tuple[int, str]]
29
+
30
+ DEFAULT_BASE_URL = "http://127.0.0.1:11434"
31
+
32
+
33
+ class OllamaPlugin(LLMPlugin):
34
+ provider = "ollama"
35
+ models = models
36
+ allow_missing_api_key = True
37
+
38
+ def __init__(self, transport: Transport | None = None):
39
+ self._transport = transport or urllib_transport
40
+
41
+ async def chat(
42
+ self,
43
+ request: UnifiedRequest,
44
+ config: ProviderConfig,
45
+ context: ChatContext,
46
+ ) -> UnifiedResponse:
47
+ base_url = self._resolve_base_url(config)
48
+ status, body = await self._request(
49
+ "POST", f"{base_url}/v1/chat/completions", self._build_body(request), config, context
50
+ )
51
+ data = self._parse_json(status, body)
52
+ choice = data["choices"][0]
53
+ message = choice["message"]
54
+ return UnifiedResponse(
55
+ id=data.get("id", ""),
56
+ model=data.get("model", context.model.id),
57
+ choices=[
58
+ UnifiedChoice(
59
+ index=choice.get("index", 0),
60
+ message=UnifiedMessage(
61
+ role="assistant",
62
+ content=message.get("content") or "",
63
+ tool_calls=tuple(
64
+ UnifiedToolCall(
65
+ id=call.get("id", ""),
66
+ type="function",
67
+ function=dict(call.get("function", {})),
68
+ )
69
+ for call in message.get("tool_calls", [])
70
+ ),
71
+ ),
72
+ finish_reason=choice.get("finish_reason") or "stop",
73
+ )
74
+ ],
75
+ usage=self._parse_usage(data.get("usage", {})),
76
+ provider_metadata=data,
77
+ )
78
+
79
+ async def chat_stream(
80
+ self,
81
+ request: UnifiedRequest,
82
+ config: ProviderConfig,
83
+ context: ChatContext,
84
+ ) -> AsyncIterator[UnifiedStreamChunk]:
85
+ base_url = self._resolve_base_url(config)
86
+ body = self._build_body(request)
87
+ body["stream"] = True
88
+ status, text = await self._request(
89
+ "POST", f"{base_url}/v1/chat/completions", body, config, context
90
+ )
91
+ if status < 200 or status >= 300:
92
+ raise PolyLLMError("PROVIDER_ERROR", f"Ollama API 错误: {status} {text}", {"status": status})
93
+ for event in parse_sse(text):
94
+ choice = (event.get("choices") or [{}])[0]
95
+ delta = choice.get("delta") or {}
96
+ yield UnifiedStreamChunk(
97
+ id=event.get("id", ""),
98
+ model=event.get("model", context.model.id),
99
+ delta=delta,
100
+ finish_reason=choice.get("finish_reason"),
101
+ )
102
+
103
+ async def list_models(self, config: ProviderConfig) -> list[ProviderModelInfo]:
104
+ base_url = self._resolve_base_url(config)
105
+ status, body = await self._request("GET", f"{base_url}/api/tags", None, config, None)
106
+ data = self._parse_json(status, body)
107
+ return [
108
+ ProviderModelInfo(
109
+ id=item.get("name") or item.get("model") or "",
110
+ display_name=item.get("name") or item.get("model"),
111
+ created_at=item.get("modified_at"),
112
+ metadata={"size": item.get("size")},
113
+ )
114
+ for item in data.get("models", [])
115
+ ]
116
+
117
+ def create_model_spec(self, model_id: str) -> ModelSpec:
118
+ return ModelSpec(
119
+ id=model_id,
120
+ provider=self.provider,
121
+ capabilities=ModelCapabilities(
122
+ streaming=True,
123
+ vision=False,
124
+ function_calling=True,
125
+ json_mode=False,
126
+ system_prompt=True,
127
+ ),
128
+ context_window=32768,
129
+ max_output=4096,
130
+ )
131
+
132
+ def _build_body(self, request: UnifiedRequest) -> dict[str, Any]:
133
+ body: dict[str, Any] = {
134
+ "model": request.model,
135
+ "messages": [
136
+ {
137
+ "role": message.role,
138
+ "content": message.content,
139
+ **({"name": message.name} if message.name else {}),
140
+ **({"tool_call_id": message.tool_call_id} if message.tool_call_id else {}),
141
+ **(
142
+ {"tool_calls": [dict(call.__dict__) for call in message.tool_calls]}
143
+ if message.tool_calls
144
+ else {}
145
+ ),
146
+ }
147
+ for message in request.messages
148
+ ],
149
+ }
150
+ if request.temperature is not None:
151
+ body["temperature"] = request.temperature
152
+ if request.max_tokens is not None:
153
+ body["max_tokens"] = request.max_tokens
154
+ if request.top_p is not None:
155
+ body["top_p"] = request.top_p
156
+ if request.tools:
157
+ body["tools"] = [{"type": "function", "function": dict(tool.function)} for tool in request.tools]
158
+ return body
159
+
160
+ def _resolve_base_url(self, config: ProviderConfig) -> str:
161
+ return (config.base_url or "").rstrip("/") or DEFAULT_BASE_URL
162
+
163
+ async def _request(
164
+ self,
165
+ method: str,
166
+ url: str,
167
+ payload: dict[str, Any] | None,
168
+ config: ProviderConfig,
169
+ context: ChatContext | None,
170
+ ) -> tuple[int, str]:
171
+ headers = dict(config.headers or {})
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(self._transport, method, url, headers, payload, timeout_ms)
176
+
177
+ @staticmethod
178
+ def _parse_usage(data: dict[str, Any]) -> UnifiedUsage:
179
+ return UnifiedUsage(
180
+ prompt_tokens=data.get("prompt_tokens", 0),
181
+ completion_tokens=data.get("completion_tokens", 0),
182
+ total_tokens=data.get("total_tokens", 0),
183
+ )
184
+
185
+ @staticmethod
186
+ def _parse_json(status: int, body: str) -> dict[str, Any]:
187
+ try:
188
+ data = cast(dict[str, Any], json.loads(body))
189
+ except json.JSONDecodeError as error:
190
+ raise PolyLLMError("PROVIDER_ERROR", f"Ollama 返回无效 JSON: {body[:200]}", {"status": status}) from error
191
+ if status < 200 or status >= 300:
192
+ raise PolyLLMError(
193
+ "PROVIDER_ERROR",
194
+ f"Ollama API 错误: {status} {body}",
195
+ {"status": status, "body": data},
196
+ )
197
+ return data
198
+
199
+
200
+ def urllib_transport(
201
+ method: str,
202
+ url: str,
203
+ headers: dict[str, str],
204
+ payload: dict[str, Any] | None,
205
+ timeout_ms: int,
206
+ ) -> tuple[int, str]:
207
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
208
+ request = Request(url, data=data, headers=headers, method=method)
209
+ try:
210
+ with urlopen(request, timeout=timeout_ms / 1000) as response:
211
+ return response.status, response.read().decode("utf-8")
212
+ except HTTPError as error:
213
+ return error.code, error.read().decode("utf-8")
214
+
215
+
216
+ def parse_sse(text: str) -> list[dict[str, Any]]:
217
+ events: list[dict[str, Any]] = []
218
+ for line in text.splitlines():
219
+ if not line.startswith("data:"):
220
+ continue
221
+ value = line.removeprefix("data:").strip()
222
+ if not value or value == "[DONE]":
223
+ continue
224
+ events.append(json.loads(value))
225
+ return events
File without changes
@@ -0,0 +1,40 @@
1
+ from polyllm_core.types import ModelCapabilities, ModelSpec, NumericParamRange
2
+
3
+ capabilities = ModelCapabilities(
4
+ streaming=True,
5
+ vision=False,
6
+ function_calling=True,
7
+ json_mode=False,
8
+ system_prompt=True,
9
+ )
10
+
11
+ models = (
12
+ ModelSpec(
13
+ id="llama3.1:8b",
14
+ provider="ollama",
15
+ aliases=("llama3.1", "llama-3.1"),
16
+ snapshot="llama3.1:8b",
17
+ capabilities=capabilities,
18
+ params={
19
+ "temperature": NumericParamRange(0, 2, 1),
20
+ "max_tokens": NumericParamRange(1, 4096, 4096, field="max_tokens"),
21
+ "top_p": NumericParamRange(0, 1, 1),
22
+ },
23
+ context_window=131072,
24
+ max_output=4096,
25
+ ),
26
+ ModelSpec(
27
+ id="qwen2.5:7b",
28
+ provider="ollama",
29
+ aliases=("qwen2.5",),
30
+ snapshot="qwen2.5:7b",
31
+ capabilities=capabilities,
32
+ params={
33
+ "temperature": NumericParamRange(0, 2, 1),
34
+ "max_tokens": NumericParamRange(1, 4096, 4096, field="max_tokens"),
35
+ "top_p": NumericParamRange(0, 1, 1),
36
+ },
37
+ context_window=32768,
38
+ max_output=4096,
39
+ ),
40
+ )
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyllm-ollama
3
+ Version: 0.3.0
4
+ Summary: Ollama (local OpenAI-compatible) 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,ollama
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.3.0
25
+ Dynamic: license-file
26
+
27
+ # PolyLLM OpenAI Plugin for Python
28
+
29
+ ```python
30
+ from polyllm_core import create_llm
31
+ from polyllm_openai import OpenAIPlugin
32
+
33
+ llm = create_llm(plugins=[OpenAIPlugin()], providers={"openai": {"api_key": "..."}})
34
+ response = await llm.chat("openai:gpt-4o-mini", messages=[{"role": "user", "content": "你好"}])
35
+ ```
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/polyllm_ollama/__init__.py
5
+ src/polyllm_ollama/plugin.py
6
+ src/polyllm_ollama/py.typed
7
+ src/polyllm_ollama/specs.py
8
+ src/polyllm_ollama.egg-info/PKG-INFO
9
+ src/polyllm_ollama.egg-info/SOURCES.txt
10
+ src/polyllm_ollama.egg-info/dependency_links.txt
11
+ src/polyllm_ollama.egg-info/requires.txt
12
+ src/polyllm_ollama.egg-info/top_level.txt
13
+ tests/test_ollama.py
@@ -0,0 +1 @@
1
+ polyllm-core>=0.3.0
@@ -0,0 +1 @@
1
+ polyllm_ollama
@@ -0,0 +1,48 @@
1
+ import asyncio
2
+ import json
3
+ import unittest
4
+
5
+ from polyllm_core.types import ChatContext, ProviderConfig, UnifiedMessage, UnifiedRequest, UnifiedTool
6
+ from polyllm_ollama import OllamaPlugin
7
+
8
+
9
+ class OllamaTests(unittest.TestCase):
10
+ def test_chat_defaults_to_local_endpoint_without_key(self):
11
+ calls = []
12
+
13
+ def transport(method, url, headers, payload, timeout):
14
+ calls.append((method, url, headers, payload, timeout))
15
+ return 200, json.dumps(
16
+ {
17
+ "id": "resp",
18
+ "model": "llama3.1:8b",
19
+ "choices": [
20
+ {"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}
21
+ ],
22
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
23
+ }
24
+ )
25
+
26
+ plugin = OllamaPlugin(transport)
27
+ response = asyncio.run(
28
+ plugin.chat(
29
+ UnifiedRequest(model="llama3.1:8b", messages=[UnifiedMessage(role="user", content="hi")]),
30
+ ProviderConfig(),
31
+ ChatContext(model=plugin.models[0]),
32
+ )
33
+ )
34
+ self.assertEqual(response.choices[0].message.content, "ok")
35
+ self.assertTrue(calls[0][1].startswith("http://127.0.0.1:11434/v1/chat/completions"))
36
+
37
+ def test_list_models_uses_native_tags_endpoint(self):
38
+ def transport(method, url, headers, payload, timeout):
39
+ self.assertEqual(method, "GET")
40
+ self.assertTrue(url.endswith("/api/tags"))
41
+ return 200, json.dumps({"models": [{"name": "llama3.1:8b", "modified_at": "2024-01-01"}]})
42
+
43
+ models = asyncio.run(OllamaPlugin(transport).list_models(ProviderConfig()))
44
+ self.assertEqual(models[0].id, "llama3.1:8b")
45
+
46
+
47
+ if __name__ == "__main__":
48
+ unittest.main()