django-openrouter 0.1.0b1__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.
Files changed (36) hide show
  1. django_openrouter-0.1.0b1/.gitignore +37 -0
  2. django_openrouter-0.1.0b1/LICENSE +21 -0
  3. django_openrouter-0.1.0b1/PKG-INFO +164 -0
  4. django_openrouter-0.1.0b1/README.md +120 -0
  5. django_openrouter-0.1.0b1/pyproject.toml +134 -0
  6. django_openrouter-0.1.0b1/src/django_openrouter/__init__.py +50 -0
  7. django_openrouter-0.1.0b1/src/django_openrouter/admin.py +274 -0
  8. django_openrouter-0.1.0b1/src/django_openrouter/apps.py +15 -0
  9. django_openrouter-0.1.0b1/src/django_openrouter/client.py +456 -0
  10. django_openrouter-0.1.0b1/src/django_openrouter/config.py +191 -0
  11. django_openrouter-0.1.0b1/src/django_openrouter/exceptions.py +35 -0
  12. django_openrouter-0.1.0b1/src/django_openrouter/fields.py +49 -0
  13. django_openrouter-0.1.0b1/src/django_openrouter/management/__init__.py +0 -0
  14. django_openrouter-0.1.0b1/src/django_openrouter/management/commands/__init__.py +0 -0
  15. django_openrouter-0.1.0b1/src/django_openrouter/management/commands/sync_models.py +32 -0
  16. django_openrouter-0.1.0b1/src/django_openrouter/migrations/0001_initial.py +261 -0
  17. django_openrouter-0.1.0b1/src/django_openrouter/migrations/__init__.py +0 -0
  18. django_openrouter-0.1.0b1/src/django_openrouter/models.py +323 -0
  19. django_openrouter-0.1.0b1/src/django_openrouter/py.typed +0 -0
  20. django_openrouter-0.1.0b1/src/django_openrouter/rules.py +76 -0
  21. django_openrouter-0.1.0b1/src/django_openrouter/signals.py +26 -0
  22. django_openrouter-0.1.0b1/src/django_openrouter/sync.py +97 -0
  23. django_openrouter-0.1.0b1/src/django_openrouter/templates/admin/django_openrouter/requestlog/change_list.html +10 -0
  24. django_openrouter-0.1.0b1/tests/__init__.py +0 -0
  25. django_openrouter-0.1.0b1/tests/conftest.py +83 -0
  26. django_openrouter-0.1.0b1/tests/settings.py +59 -0
  27. django_openrouter-0.1.0b1/tests/test_admin.py +233 -0
  28. django_openrouter-0.1.0b1/tests/test_client.py +360 -0
  29. django_openrouter-0.1.0b1/tests/test_config.py +101 -0
  30. django_openrouter-0.1.0b1/tests/test_fields.py +20 -0
  31. django_openrouter-0.1.0b1/tests/test_migrations.py +23 -0
  32. django_openrouter-0.1.0b1/tests/test_models.py +152 -0
  33. django_openrouter-0.1.0b1/tests/test_package.py +18 -0
  34. django_openrouter-0.1.0b1/tests/test_rules.py +90 -0
  35. django_openrouter-0.1.0b1/tests/test_sync_models.py +106 -0
  36. django_openrouter-0.1.0b1/tests/urls.py +6 -0
@@ -0,0 +1,37 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.egg-info/
6
+ .eggs/
7
+ dist/
8
+ build/
9
+ *.egg
10
+
11
+ # Virtualenv
12
+ .venv/
13
+ venv/
14
+ env/
15
+
16
+ # Test / lint
17
+ .pytest_cache/
18
+ .mypy_cache/
19
+ .ruff_cache/
20
+ .coverage
21
+ .coverage.*
22
+ htmlcov/
23
+ .tox/
24
+ .nox/
25
+
26
+ # Django
27
+ *.sqlite3
28
+ db.sqlite3
29
+
30
+ # IDE
31
+ .idea/
32
+ .vscode/
33
+ *.swp
34
+
35
+ # OS
36
+ .DS_Store
37
+ Thumbs.db
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 django-openrouter 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,164 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-openrouter
3
+ Version: 0.1.0b1
4
+ Summary: Reusable Django app for managing OpenRouter models, budgets and usage via the admin.
5
+ Project-URL: Homepage, https://github.com/django-openrouter/django-openrouter
6
+ Project-URL: Documentation, https://github.com/django-openrouter/django-openrouter#readme
7
+ Author: django-openrouter contributors
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: chat,django,llm,openai,openrouter
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4.2
15
+ Classifier: Framework :: Django :: 5.0
16
+ Classifier: Framework :: Django :: 5.1
17
+ Classifier: Framework :: Django :: 5.2
18
+ Classifier: Framework :: Django :: 6.0
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Classifier: Operating System :: OS Independent
22
+ Classifier: Programming Language :: Python
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Topic :: Internet :: WWW/HTTP
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.11
30
+ Requires-Dist: django>=4.2
31
+ Requires-Dist: httpx>=0.27
32
+ Provides-Extra: async
33
+ Requires-Dist: httpx>=0.27; extra == 'async'
34
+ Provides-Extra: dev
35
+ Requires-Dist: django-stubs>=5.0; extra == 'dev'
36
+ Requires-Dist: mypy>=1.11; extra == 'dev'
37
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
38
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
39
+ Requires-Dist: pytest-django>=4.8; extra == 'dev'
40
+ Requires-Dist: pytest>=8.0; extra == 'dev'
41
+ Requires-Dist: respx>=0.21; extra == 'dev'
42
+ Requires-Dist: ruff>=0.6; extra == 'dev'
43
+ Description-Content-Type: text/markdown
44
+
45
+ # django-openrouter
46
+
47
+ Reusable Django application for managing [OpenRouter](https://openrouter.ai) models, usage profiles, budgets and request logs from Django admin.
48
+
49
+ Your product code (translation, chat, summarization, …) talks to OpenRouter through this library instead of hardcoded `settings.py` keys and model ids. An operator picks active models, sets daily/monthly limits, and inspects spend in admin.
50
+
51
+ ## Why not `settings.py`?
52
+
53
+ Hardcoding `OPENROUTER_MODEL = "anthropic/claude-3.5-sonnet"` means a deploy to change models, budgets or a kill switch. `django-openrouter` stores that runtime policy in the database, caches it, and enforces limits before every request.
54
+
55
+ API keys can still come from the environment (`OPENROUTER_API_KEY`) if you prefer not to keep them in the database.
56
+
57
+ ## Quickstart
58
+
59
+ ### 1. Install
60
+
61
+ ```bash
62
+ pip install django-openrouter
63
+ ```
64
+
65
+ ### 2. Enable the app and migrate
66
+
67
+ ```python
68
+ # settings.py
69
+ INSTALLED_APPS = [
70
+ ...,
71
+ "django_openrouter",
72
+ ]
73
+ ```
74
+
75
+ ```bash
76
+ python manage.py migrate
77
+ ```
78
+
79
+ ### 3. Configure in Django admin
80
+
81
+ 1. Open **OpenRouter → OpenRouter settings**. Paste an API key *or* leave it empty and set `OPENROUTER_API_KEY` in the environment.
82
+ 2. Run `python manage.py sync_models` to pull the model catalog (`GET /api/v1/models`).
83
+ 3. Create a **Usage profile** (slug `translation`, `chat`, …), pick a model, optional fallbacks, limits and budgets.
84
+ 4. Set that profile as **default profile** if you want `chat(messages=...)` without a name.
85
+
86
+ ## Usage
87
+
88
+ ```python
89
+ from django_openrouter import chat
90
+
91
+ result = chat(
92
+ "translation",
93
+ messages=[{"role": "user", "content": "Translate to French: hello"}],
94
+ )
95
+ print(result.content)
96
+ print(result.model_used, result.cost_usd, result.latency_ms)
97
+ ```
98
+
99
+ Sync client:
100
+
101
+ ```python
102
+ from django_openrouter import OpenRouterClient
103
+
104
+ client = OpenRouterClient("chat")
105
+ result = client.chat(messages=[{"role": "user", "content": "Hello"}])
106
+ ```
107
+
108
+ Async:
109
+
110
+ ```python
111
+ from django_openrouter import achat
112
+
113
+ result = await achat("chat", messages=[{"role": "user", "content": "Hello"}])
114
+ ```
115
+
116
+ If a profile’s limit or budget is exhausted, `chat()` raises `BudgetExceeded` or `RateLimitExceeded` and **does not** silently fall back. Fallback models are only used when OpenRouter returns `402`, `429` or `5xx`.
117
+
118
+ Streaming (`stream=True`) raises `NotImplementedError` in this MVP.
119
+
120
+ ## Management command
121
+
122
+ ```bash
123
+ python manage.py sync_models
124
+ python manage.py sync_models --api-key sk-or-...
125
+ ```
126
+
127
+ Upserts the catalog, never deletes rows, and sets `is_active=False` on models that disappeared from OpenRouter.
128
+
129
+ ## `settings.OPENROUTER`
130
+
131
+ | Key | Default | Description |
132
+ | --- | --- | --- |
133
+ | `CACHE_TIMEOUT` | `60` | Seconds to keep runtime config in Django’s cache |
134
+ | `CACHE_ALIAS` | `"default"` | Cache alias (`django.core.cache`) |
135
+ | `API_KEY` | unset | Fallback API key if the admin field is empty |
136
+ | `HTTP_REFERER` | unset | Sent as `HTTP-Referer` (OpenRouter app attribution) |
137
+ | `X_TITLE` | unset | Sent as `X-Title` |
138
+
139
+ Also accepted, in this order, when the admin API key is empty:
140
+
141
+ 1. `settings.OPENROUTER["API_KEY"]`
142
+ 2. `settings.OPENROUTER_API_KEY`
143
+ 3. Environment variable `OPENROUTER_API_KEY`
144
+
145
+ Example:
146
+
147
+ ```python
148
+ OPENROUTER = {
149
+ "CACHE_TIMEOUT": 60,
150
+ "CACHE_ALIAS": "default",
151
+ "HTTP_REFERER": "https://my-app.example",
152
+ "X_TITLE": "My App",
153
+ }
154
+ ```
155
+
156
+ The default cache backend (`LocMemCache`) is enough. Redis/Memcached are optional.
157
+
158
+ ## Limits
159
+
160
+ Usage is aggregated from `RequestLog` for the current calendar day and month (`UsageProfile.get_usage("day"|"month")`). Null limit fields mean “unlimited”.
161
+
162
+ ## License
163
+
164
+ MIT
@@ -0,0 +1,120 @@
1
+ # django-openrouter
2
+
3
+ Reusable Django application for managing [OpenRouter](https://openrouter.ai) models, usage profiles, budgets and request logs from Django admin.
4
+
5
+ Your product code (translation, chat, summarization, …) talks to OpenRouter through this library instead of hardcoded `settings.py` keys and model ids. An operator picks active models, sets daily/monthly limits, and inspects spend in admin.
6
+
7
+ ## Why not `settings.py`?
8
+
9
+ Hardcoding `OPENROUTER_MODEL = "anthropic/claude-3.5-sonnet"` means a deploy to change models, budgets or a kill switch. `django-openrouter` stores that runtime policy in the database, caches it, and enforces limits before every request.
10
+
11
+ API keys can still come from the environment (`OPENROUTER_API_KEY`) if you prefer not to keep them in the database.
12
+
13
+ ## Quickstart
14
+
15
+ ### 1. Install
16
+
17
+ ```bash
18
+ pip install django-openrouter
19
+ ```
20
+
21
+ ### 2. Enable the app and migrate
22
+
23
+ ```python
24
+ # settings.py
25
+ INSTALLED_APPS = [
26
+ ...,
27
+ "django_openrouter",
28
+ ]
29
+ ```
30
+
31
+ ```bash
32
+ python manage.py migrate
33
+ ```
34
+
35
+ ### 3. Configure in Django admin
36
+
37
+ 1. Open **OpenRouter → OpenRouter settings**. Paste an API key *or* leave it empty and set `OPENROUTER_API_KEY` in the environment.
38
+ 2. Run `python manage.py sync_models` to pull the model catalog (`GET /api/v1/models`).
39
+ 3. Create a **Usage profile** (slug `translation`, `chat`, …), pick a model, optional fallbacks, limits and budgets.
40
+ 4. Set that profile as **default profile** if you want `chat(messages=...)` without a name.
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ from django_openrouter import chat
46
+
47
+ result = chat(
48
+ "translation",
49
+ messages=[{"role": "user", "content": "Translate to French: hello"}],
50
+ )
51
+ print(result.content)
52
+ print(result.model_used, result.cost_usd, result.latency_ms)
53
+ ```
54
+
55
+ Sync client:
56
+
57
+ ```python
58
+ from django_openrouter import OpenRouterClient
59
+
60
+ client = OpenRouterClient("chat")
61
+ result = client.chat(messages=[{"role": "user", "content": "Hello"}])
62
+ ```
63
+
64
+ Async:
65
+
66
+ ```python
67
+ from django_openrouter import achat
68
+
69
+ result = await achat("chat", messages=[{"role": "user", "content": "Hello"}])
70
+ ```
71
+
72
+ If a profile’s limit or budget is exhausted, `chat()` raises `BudgetExceeded` or `RateLimitExceeded` and **does not** silently fall back. Fallback models are only used when OpenRouter returns `402`, `429` or `5xx`.
73
+
74
+ Streaming (`stream=True`) raises `NotImplementedError` in this MVP.
75
+
76
+ ## Management command
77
+
78
+ ```bash
79
+ python manage.py sync_models
80
+ python manage.py sync_models --api-key sk-or-...
81
+ ```
82
+
83
+ Upserts the catalog, never deletes rows, and sets `is_active=False` on models that disappeared from OpenRouter.
84
+
85
+ ## `settings.OPENROUTER`
86
+
87
+ | Key | Default | Description |
88
+ | --- | --- | --- |
89
+ | `CACHE_TIMEOUT` | `60` | Seconds to keep runtime config in Django’s cache |
90
+ | `CACHE_ALIAS` | `"default"` | Cache alias (`django.core.cache`) |
91
+ | `API_KEY` | unset | Fallback API key if the admin field is empty |
92
+ | `HTTP_REFERER` | unset | Sent as `HTTP-Referer` (OpenRouter app attribution) |
93
+ | `X_TITLE` | unset | Sent as `X-Title` |
94
+
95
+ Also accepted, in this order, when the admin API key is empty:
96
+
97
+ 1. `settings.OPENROUTER["API_KEY"]`
98
+ 2. `settings.OPENROUTER_API_KEY`
99
+ 3. Environment variable `OPENROUTER_API_KEY`
100
+
101
+ Example:
102
+
103
+ ```python
104
+ OPENROUTER = {
105
+ "CACHE_TIMEOUT": 60,
106
+ "CACHE_ALIAS": "default",
107
+ "HTTP_REFERER": "https://my-app.example",
108
+ "X_TITLE": "My App",
109
+ }
110
+ ```
111
+
112
+ The default cache backend (`LocMemCache`) is enough. Redis/Memcached are optional.
113
+
114
+ ## Limits
115
+
116
+ Usage is aggregated from `RequestLog` for the current calendar day and month (`UsageProfile.get_usage("day"|"month")`). Null limit fields mean “unlimited”.
117
+
118
+ ## License
119
+
120
+ MIT
@@ -0,0 +1,134 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "django-openrouter"
7
+ dynamic = ["version"]
8
+ description = "Reusable Django app for managing OpenRouter models, budgets and usage via the admin."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "django-openrouter contributors" }]
13
+ keywords = ["django", "openrouter", "llm", "openai", "chat"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Web Environment",
17
+ "Framework :: Django",
18
+ "Framework :: Django :: 4.2",
19
+ "Framework :: Django :: 5.0",
20
+ "Framework :: Django :: 5.1",
21
+ "Framework :: Django :: 5.2",
22
+ "Framework :: Django :: 6.0",
23
+ "Intended Audience :: Developers",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python",
27
+ "Programming Language :: Python :: 3",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Topic :: Internet :: WWW/HTTP",
32
+ "Typing :: Typed",
33
+ ]
34
+ dependencies = [
35
+ "django>=4.2",
36
+ "httpx>=0.27",
37
+ ]
38
+
39
+ [project.optional-dependencies]
40
+ async = ["httpx>=0.27"]
41
+ dev = [
42
+ "pytest>=8.0",
43
+ "pytest-asyncio>=0.24",
44
+ "pytest-cov>=5.0",
45
+ "pytest-django>=4.8",
46
+ "respx>=0.21",
47
+ "ruff>=0.6",
48
+ "mypy>=1.11",
49
+ "django-stubs>=5.0",
50
+ ]
51
+
52
+ [project.urls]
53
+ Homepage = "https://github.com/django-openrouter/django-openrouter"
54
+ Documentation = "https://github.com/django-openrouter/django-openrouter#readme"
55
+
56
+ [tool.hatch.version]
57
+ path = "src/django_openrouter/__init__.py"
58
+
59
+ [tool.hatch.build.targets.sdist]
60
+ include = [
61
+ "/src",
62
+ "/tests",
63
+ "/README.md",
64
+ "/LICENSE",
65
+ ]
66
+
67
+ [tool.hatch.build.targets.wheel]
68
+ packages = ["src/django_openrouter"]
69
+
70
+ [tool.pytest.ini_options]
71
+ DJANGO_SETTINGS_MODULE = "tests.settings"
72
+ pythonpath = ["src", "."]
73
+ testpaths = ["tests"]
74
+ asyncio_mode = "auto"
75
+ addopts = "-q --strict-markers"
76
+ filterwarnings = [
77
+ "error",
78
+ "ignore::DeprecationWarning",
79
+ "ignore::PendingDeprecationWarning",
80
+ ]
81
+
82
+ [tool.coverage.run]
83
+ branch = true
84
+ source = ["django_openrouter"]
85
+ omit = [
86
+ "*/migrations/*",
87
+ "*/tests/*",
88
+ ]
89
+
90
+ [tool.coverage.report]
91
+ show_missing = true
92
+ skip_covered = false
93
+ fail_under = 85
94
+ exclude_lines = [
95
+ "pragma: no cover",
96
+ "if TYPE_CHECKING:",
97
+ "raise NotImplementedError",
98
+ ]
99
+
100
+ [tool.ruff]
101
+ target-version = "py311"
102
+ line-length = 99
103
+ src = ["src", "tests"]
104
+
105
+ [tool.ruff.lint]
106
+ select = ["E", "F", "I", "UP", "B", "DJ", "RUF"]
107
+ ignore = ["RUF012", "RUF002"]
108
+
109
+ [tool.ruff.lint.isort]
110
+ known-first-party = ["django_openrouter"]
111
+
112
+ [tool.ruff.lint.per-file-ignores]
113
+ "src/django_openrouter/migrations/*" = ["E501", "I001"]
114
+ "tests/*" = ["DJ01"]
115
+
116
+ [tool.mypy]
117
+ python_version = "3.11"
118
+ plugins = ["mypy_django_plugin.main"]
119
+ pretty = true
120
+ show_error_codes = true
121
+ warn_unused_ignores = true
122
+ warn_redundant_casts = true
123
+ warn_unused_configs = true
124
+ disallow_untyped_defs = true
125
+ check_untyped_defs = true
126
+ no_implicit_optional = true
127
+ exclude = ["src/django_openrouter/migrations/"]
128
+
129
+ [[tool.mypy.overrides]]
130
+ module = "tests.*"
131
+ disallow_untyped_defs = false
132
+
133
+ [tool.django-stubs]
134
+ django_settings_module = "tests.settings"
@@ -0,0 +1,50 @@
1
+ """django-openrouter — reusable Django app for OpenRouter models, budgets and usage logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ __version__ = "0.1.0b1"
8
+ default_app_config = "django_openrouter.apps.DjangoOpenRouterConfig"
9
+
10
+ if TYPE_CHECKING:
11
+ from django_openrouter.client import (
12
+ AsyncOpenRouterClient as AsyncOpenRouterClient,
13
+ )
14
+ from django_openrouter.client import (
15
+ ChatResult as ChatResult,
16
+ )
17
+ from django_openrouter.client import (
18
+ OpenRouterClient as OpenRouterClient,
19
+ )
20
+ from django_openrouter.client import (
21
+ achat as achat,
22
+ )
23
+ from django_openrouter.client import (
24
+ chat as chat,
25
+ )
26
+
27
+ __all__ = [
28
+ "AsyncOpenRouterClient",
29
+ "ChatResult",
30
+ "OpenRouterClient",
31
+ "__version__",
32
+ "achat",
33
+ "chat",
34
+ ]
35
+
36
+
37
+ def __getattr__(name: str) -> Any:
38
+ # Ленивый импорт, чтобы версия пакета читалась без django.setup().
39
+ if name in {"AsyncOpenRouterClient", "ChatResult", "OpenRouterClient", "achat", "chat"}:
40
+ from django_openrouter import client as client_module
41
+
42
+ mapping = {
43
+ "AsyncOpenRouterClient": client_module.AsyncOpenRouterClient,
44
+ "ChatResult": client_module.ChatResult,
45
+ "OpenRouterClient": client_module.OpenRouterClient,
46
+ "achat": client_module.achat,
47
+ "chat": client_module.chat,
48
+ }
49
+ return mapping[name]
50
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")