genkit-django 0.9.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,36 @@
1
+ *$py.class
2
+ *.egg
3
+ *.egg-info/
4
+ *.py[cod]
5
+ *.so
6
+ .DS_Store
7
+ .Python
8
+ .cache/
9
+ .coverage
10
+ .eggs/
11
+ .genkit
12
+ .idea/
13
+ .installed.cfg
14
+ .mypy_cache/
15
+ .pytest_cache/
16
+ .ruff_cache/
17
+ .venv
18
+ ENV/
19
+ __pycache__/
20
+ build/
21
+ develop-eggs/
22
+ dist/
23
+ downloads/
24
+ eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ site/
30
+ var/
31
+ venv/
32
+ wheels/
33
+ .gemini/artifacts/
34
+
35
+ *.bak
36
+ release-manifest.json
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Google LLC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: genkit-django
3
+ Version: 0.9.0
4
+ Summary: Genkit Django Plugin
5
+ Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit/issues
6
+ Project-URL: Documentation, https://firebase.google.com/docs/genkit
7
+ Project-URL: Homepage, https://github.com/genkit-ai/genkit
8
+ Project-URL: Repository, https://github.com/genkit-ai/genkit/tree/main/py
9
+ Author: Google
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: ai,artificial-intelligence,async,django,generative-ai,genkit,llm,machine-learning,server,web
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Environment :: Web Environment
16
+ Classifier: Framework :: AsyncIO
17
+ Classifier: Framework :: Django
18
+ Classifier: Framework :: Django :: 4.2
19
+ Classifier: Framework :: Django :: 5.0
20
+ Classifier: Framework :: Django :: 5.1
21
+ Classifier: Framework :: Pydantic
22
+ Classifier: Framework :: Pydantic :: 2
23
+ Classifier: Intended Audience :: Developers
24
+ Classifier: License :: OSI Approved :: Apache Software License
25
+ Classifier: Operating System :: OS Independent
26
+ Classifier: Programming Language :: Python
27
+ Classifier: Programming Language :: Python :: 3 :: Only
28
+ Classifier: Programming Language :: Python :: 3.10
29
+ Classifier: Programming Language :: Python :: 3.11
30
+ Classifier: Programming Language :: Python :: 3.12
31
+ Classifier: Programming Language :: Python :: 3.13
32
+ Classifier: Programming Language :: Python :: 3.14
33
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
34
+ Classifier: Topic :: Software Development :: Libraries
35
+ Classifier: Typing :: Typed
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: django>=4.2
38
+ Requires-Dist: genkit
39
+ Requires-Dist: pydantic>=2.10.5
40
+ Description-Content-Type: text/markdown
41
+
42
+ # Genkit Django Plugin
43
+
44
+ `genkit-django` exposes Genkit flows as HTTP endpoints in a Django application. It mirrors `genkit-flask` and `genkit-fastapi`: one decorator turns a `@ai.flow()` into a Django view that speaks the Genkit HTTP protocol (JSON envelope, optional SSE streaming, structured error responses).
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ uv add genkit-django
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ # myapp/views.py
56
+ from genkit import Genkit
57
+ from genkit_django import genkit_django_handler
58
+
59
+ ai = Genkit(plugins=[...])
60
+
61
+
62
+ @genkit_django_handler(ai)
63
+ @ai.flow()
64
+ async def chat(prompt: str) -> str:
65
+ response = await ai.generate(prompt=prompt)
66
+ return response.text
67
+ ```
68
+
69
+ ```python
70
+ # myproject/urls.py
71
+ from django.urls import path
72
+ from myapp.views import chat
73
+
74
+ urlpatterns = [
75
+ path('chat/', chat),
76
+ ]
77
+ ```
78
+
79
+ The view requires Django's ASGI server (Django 4.1+):
80
+
81
+ ```bash
82
+ uvicorn myproject.asgi:application
83
+ ```
84
+
85
+ ## Wire protocol
86
+
87
+ - Body: `{"data": <flow_input>}`. Missing `data` → 400.
88
+ - Streaming: `Accept: text/event-stream` or `?stream=true`. Each chunk emits `data: {"message": ...}\n\n`; completion emits `data: {"result": ...}\n\n`; on exception `error: {"error": ...}`.
89
+ - Non-stream: `{"result": <flow_output>}` on success; 500 with `HttpErrorWireFormat` JSON on exception.
90
+
91
+ ## Context provider
92
+
93
+ ```python
94
+ async def auth(request_data):
95
+ return {'username': request_data.headers.get('authorization')}
96
+
97
+
98
+ @genkit_django_handler(ai, context_provider=auth)
99
+ @ai.flow()
100
+ async def chat(prompt, ctx):
101
+ user = ctx.context.get('username')
102
+ ...
103
+ ```
@@ -0,0 +1,62 @@
1
+ # Genkit Django Plugin
2
+
3
+ `genkit-django` exposes Genkit flows as HTTP endpoints in a Django application. It mirrors `genkit-flask` and `genkit-fastapi`: one decorator turns a `@ai.flow()` into a Django view that speaks the Genkit HTTP protocol (JSON envelope, optional SSE streaming, structured error responses).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ uv add genkit-django
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ # myapp/views.py
15
+ from genkit import Genkit
16
+ from genkit_django import genkit_django_handler
17
+
18
+ ai = Genkit(plugins=[...])
19
+
20
+
21
+ @genkit_django_handler(ai)
22
+ @ai.flow()
23
+ async def chat(prompt: str) -> str:
24
+ response = await ai.generate(prompt=prompt)
25
+ return response.text
26
+ ```
27
+
28
+ ```python
29
+ # myproject/urls.py
30
+ from django.urls import path
31
+ from myapp.views import chat
32
+
33
+ urlpatterns = [
34
+ path('chat/', chat),
35
+ ]
36
+ ```
37
+
38
+ The view requires Django's ASGI server (Django 4.1+):
39
+
40
+ ```bash
41
+ uvicorn myproject.asgi:application
42
+ ```
43
+
44
+ ## Wire protocol
45
+
46
+ - Body: `{"data": <flow_input>}`. Missing `data` → 400.
47
+ - Streaming: `Accept: text/event-stream` or `?stream=true`. Each chunk emits `data: {"message": ...}\n\n`; completion emits `data: {"result": ...}\n\n`; on exception `error: {"error": ...}`.
48
+ - Non-stream: `{"result": <flow_output>}` on success; 500 with `HttpErrorWireFormat` JSON on exception.
49
+
50
+ ## Context provider
51
+
52
+ ```python
53
+ async def auth(request_data):
54
+ return {'username': request_data.headers.get('authorization')}
55
+
56
+
57
+ @genkit_django_handler(ai, context_provider=auth)
58
+ @ai.flow()
59
+ async def chat(prompt, ctx):
60
+ user = ctx.context.get('username')
61
+ ...
62
+ ```
@@ -0,0 +1,80 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ [project]
18
+ authors = [{ name = "Google" }]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Environment :: Console",
22
+ "Environment :: Web Environment",
23
+ "Framework :: AsyncIO",
24
+ "Framework :: Django",
25
+ "Framework :: Django :: 4.2",
26
+ "Framework :: Django :: 5.0",
27
+ "Framework :: Django :: 5.1",
28
+ "Framework :: Pydantic",
29
+ "Framework :: Pydantic :: 2",
30
+ "Intended Audience :: Developers",
31
+ "Operating System :: OS Independent",
32
+ "Programming Language :: Python",
33
+ "Programming Language :: Python :: 3 :: Only",
34
+ "Programming Language :: Python :: 3.10",
35
+ "Programming Language :: Python :: 3.11",
36
+ "Programming Language :: Python :: 3.12",
37
+ "Programming Language :: Python :: 3.13",
38
+ "Programming Language :: Python :: 3.14",
39
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
40
+ "Topic :: Software Development :: Libraries",
41
+ "Typing :: Typed",
42
+ "License :: OSI Approved :: Apache Software License",
43
+ ]
44
+ dependencies = [
45
+ "genkit",
46
+ "pydantic>=2.10.5",
47
+ "django>=4.2",
48
+ ]
49
+ description = "Genkit Django Plugin"
50
+ keywords = [
51
+ "genkit",
52
+ "ai",
53
+ "llm",
54
+ "machine-learning",
55
+ "artificial-intelligence",
56
+ "generative-ai",
57
+ "django",
58
+ "web",
59
+ "server",
60
+ "async",
61
+ ]
62
+ license = "Apache-2.0"
63
+ name = "genkit-django"
64
+ readme = "README.md"
65
+ requires-python = ">=3.10"
66
+ version = "0.9.0"
67
+
68
+ [project.urls]
69
+ "Bug Tracker" = "https://github.com/genkit-ai/genkit/issues"
70
+ "Documentation" = "https://firebase.google.com/docs/genkit"
71
+ "Homepage" = "https://github.com/genkit-ai/genkit"
72
+ "Repository" = "https://github.com/genkit-ai/genkit/tree/main/py"
73
+
74
+ [build-system]
75
+ build-backend = "hatchling.build"
76
+ requires = ["hatchling"]
77
+
78
+ [tool.hatch.build.targets.wheel]
79
+ only-include = ["src/genkit_django"]
80
+ sources = ["src"]
@@ -0,0 +1,94 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Django Plugin for Genkit.
19
+
20
+ This plugin provides Django integration for Genkit, enabling you to expose
21
+ Genkit flows as HTTP endpoints in a Django ASGI application.
22
+
23
+ Example:
24
+ ```python
25
+ # myapp/views.py
26
+ from genkit import Genkit
27
+ from genkit_django import genkit_django_handler
28
+ from genkit_google_genai import GoogleAI
29
+
30
+ # 1. Initialize Genkit
31
+ ai = Genkit(plugins=[GoogleAI()])
32
+
33
+
34
+ # 2. Define flow and decorate as Django view
35
+ @genkit_django_handler(ai)
36
+ @ai.flow()
37
+ async def chat(prompt: str) -> str:
38
+ res = await ai.generate(
39
+ model='googleai/gemini-flash-latest',
40
+ prompt=f'Answer concisely: {prompt}',
41
+ )
42
+ return res.text
43
+
44
+
45
+ # POST /chat/ {"data": "Hello!"}
46
+ # => {"result": "Hi there! How can I assist you today?"}
47
+ ```
48
+
49
+ ```python
50
+ # myproject/urls.py
51
+ from django.urls import path
52
+ from myapp.views import chat
53
+
54
+ urlpatterns = [
55
+ path('chat/', chat),
56
+ ]
57
+ ```
58
+
59
+ Requirements:
60
+ - Django 4.1+ (async views require ASGI)
61
+ - An ASGI server such as ``uvicorn`` or ``daphne``:
62
+
63
+ ```bash
64
+ uvicorn myproject.asgi:application
65
+ ```
66
+
67
+ Wire protocol:
68
+ - Body: ``{"data": <flow_input>}``. Missing ``data`` returns 400.
69
+ - Streaming: ``Accept: text/event-stream`` or ``?stream=true`` returns
70
+ ``text/event-stream`` with ``data: {"message": ...}`` chunks and a
71
+ final ``data: {"result": ...}`` event.
72
+ - Non-stream: ``{"result": <flow_output>}`` on success; 500 with
73
+ ``HttpErrorWireFormat`` JSON on exception.
74
+
75
+ The returned view is automatically ``csrf_exempt`` because this is a JSON API.
76
+
77
+ See Also:
78
+ - Django ASGI: https://docs.djangoproject.com/en/stable/howto/deployment/asgi/
79
+ - Genkit documentation: https://genkit.dev/
80
+ """
81
+
82
+ from .handler import genkit_django_handler
83
+
84
+
85
+ def package_name() -> str:
86
+ """Get the package name for the Django plugin.
87
+
88
+ Returns:
89
+ The fully qualified package name as a string.
90
+ """
91
+ return 'genkit_django'
92
+
93
+
94
+ __all__ = ['package_name', genkit_django_handler.__name__]
@@ -0,0 +1,204 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Genkit Django handler for serving flows as HTTP endpoints."""
18
+
19
+ import asyncio
20
+ import json
21
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
22
+ from typing import Any, cast
23
+
24
+ from django.http import HttpRequest, HttpResponse, HttpResponseBase, JsonResponse, StreamingHttpResponse
25
+ from django.views.decorators.csrf import csrf_exempt
26
+ from pydantic import BaseModel
27
+
28
+ from genkit import Action, Genkit, GenkitError
29
+ from genkit.plugin_api import ContextProvider, RequestData, get_callable_json
30
+
31
+ # Compact JSON (no spaces) for smaller wire payload.
32
+ _JSON_SEPARATORS = (',', ':')
33
+
34
+
35
+ def _to_dict(obj: Any) -> Any: # noqa: ANN401
36
+ """Recursively convert Pydantic models inside ``obj`` to plain JSON-friendly types.
37
+
38
+ Flows can return a Pydantic model, a list of Pydantic models, or a dict whose
39
+ values are Pydantic models. Django's ``JsonResponse`` and ``json.dumps`` don't
40
+ know how to serialize ``BaseModel`` instances natively, so descend into lists,
41
+ tuples, and dicts to convert every model we find.
42
+ """
43
+ if isinstance(obj, BaseModel):
44
+ return obj.model_dump()
45
+ if isinstance(obj, list):
46
+ return [_to_dict(item) for item in obj]
47
+ if isinstance(obj, tuple):
48
+ return [_to_dict(item) for item in obj]
49
+ if isinstance(obj, dict):
50
+ return {k: _to_dict(v) for k, v in obj.items()}
51
+ return obj
52
+
53
+
54
+ def _unwrap_cause(e: Exception) -> Exception:
55
+ """Return the ``cause`` of a GenkitError when available, else the exception itself.
56
+
57
+ ``GenkitError.cause`` is typed ``Exception | None``: classes like ``PublicError``
58
+ pass no cause, so unwrapping unconditionally would yield ``None`` and lose the
59
+ original error details.
60
+ """
61
+ if isinstance(e, GenkitError) and e.cause is not None:
62
+ return e.cause
63
+ return e
64
+
65
+
66
+ def _error_response(status: int, err: Exception) -> HttpResponse:
67
+ """Return a JSON HttpErrorWireFormat response for an exception."""
68
+ return HttpResponse(
69
+ status=status,
70
+ content=json.dumps(get_callable_json(err), separators=_JSON_SEPARATORS), # pyright: ignore[reportArgumentType]
71
+ content_type='application/json',
72
+ )
73
+
74
+
75
+ def _request_headers(request: HttpRequest) -> Mapping[str, str]:
76
+ """Return ``request.headers`` typed as a Mapping.
77
+
78
+ Django's ``HttpRequest.headers`` is a ``HttpHeaders`` (a ``CaseInsensitiveMapping``)
79
+ at runtime but is exposed as a ``cached_property`` to static type checkers, which
80
+ then can't see ``.get()`` / ``.items()``. Casting once keeps the handler readable.
81
+ """
82
+ return cast(Mapping[str, str], request.headers)
83
+
84
+
85
+ class _DjangoRequestData(RequestData):
86
+ """Wraps Django request data for Genkit context."""
87
+
88
+ def __init__(self, request: HttpRequest, body: dict[str, Any] | None) -> None:
89
+ super().__init__(request=request)
90
+ self.method = request.method
91
+ self.headers = {k.lower(): v for k, v in _request_headers(request).items()}
92
+ self.input = body.get('data') if body else None
93
+
94
+
95
+ def genkit_django_handler(
96
+ ai: Genkit,
97
+ context_provider: ContextProvider | None = None,
98
+ ) -> Callable[[Action], Callable[[HttpRequest], Awaitable[HttpResponseBase]]]:
99
+ """A decorator for serving Genkit flows via a Django ASGI app.
100
+
101
+ ```python
102
+ from django.urls import path
103
+ from genkit_django import genkit_django_handler
104
+
105
+
106
+ @genkit_django_handler(ai)
107
+ @ai.flow()
108
+ async def say_hi(name: str, ctx):
109
+ return await ai.generate(
110
+ on_chunk=ctx.send_chunk,
111
+ prompt=f'tell a medium sized joke about {name}',
112
+ )
113
+
114
+
115
+ urlpatterns = [
116
+ path('chat/', say_hi),
117
+ ]
118
+ ```
119
+
120
+ Requires Django ASGI (Django 4.1+). The returned view is `csrf_exempt`
121
+ because this is a JSON API.
122
+
123
+ Args:
124
+ ai: The Genkit instance.
125
+ context_provider: Optional function to extract context from the request.
126
+
127
+ Returns:
128
+ A decorator that wraps an Action and returns an async Django view.
129
+ """
130
+
131
+ def decorator(flow: Action) -> Callable[[HttpRequest], Awaitable[HttpResponseBase]]:
132
+ if not isinstance(flow, Action):
133
+ raise GenkitError(status='INVALID_ARGUMENT', message='must apply @genkit_django_handler on a @flow')
134
+
135
+ @csrf_exempt
136
+ async def handler(request: HttpRequest) -> HttpResponseBase:
137
+ if request.method != 'POST':
138
+ return _error_response(
139
+ 405,
140
+ GenkitError(status='INVALID_ARGUMENT', message='only POST is supported'),
141
+ )
142
+
143
+ try:
144
+ body = json.loads(request.body.decode('utf-8')) if request.body else {}
145
+ except (json.JSONDecodeError, UnicodeDecodeError):
146
+ return _error_response(
147
+ 400,
148
+ GenkitError(status='INVALID_ARGUMENT', message='request body must be valid JSON'),
149
+ )
150
+
151
+ if not isinstance(body, dict) or 'data' not in body:
152
+ return _error_response(
153
+ 400,
154
+ GenkitError(
155
+ status='INVALID_ARGUMENT',
156
+ message='Action request must be wrapped in {"data": ...} object',
157
+ ),
158
+ )
159
+
160
+ request_data = _DjangoRequestData(request, body)
161
+ action_context: dict[str, object] | None = None
162
+
163
+ if context_provider:
164
+ try:
165
+ context = context_provider(request_data)
166
+ if asyncio.iscoroutine(context):
167
+ context = await context
168
+ if isinstance(context, dict):
169
+ action_context = context
170
+ except Exception as e:
171
+ return _error_response(500, _unwrap_cause(e))
172
+
173
+ accept = _request_headers(request).get('Accept', '')
174
+ stream = 'text/event-stream' in accept or request.GET.get('stream') == 'true'
175
+ init = body.get('init')
176
+
177
+ if stream:
178
+
179
+ async def event_stream() -> AsyncIterator[str]:
180
+ try:
181
+ stream_response = flow.stream(body.get('data'), context=action_context, init=init)
182
+ async for chunk in stream_response.stream:
183
+ yield f'data: {json.dumps({"message": _to_dict(chunk)}, separators=_JSON_SEPARATORS)}\n\n'
184
+
185
+ result = await stream_response.response
186
+ yield f'data: {json.dumps({"result": _to_dict(result)}, separators=_JSON_SEPARATORS)}\n\n'
187
+ except Exception as e:
188
+ err_payload = json.dumps(
189
+ {'error': get_callable_json(_unwrap_cause(e))},
190
+ separators=_JSON_SEPARATORS,
191
+ )
192
+ yield f'data: {err_payload}\n\n'
193
+
194
+ return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
195
+
196
+ try:
197
+ response = await flow.run(body.get('data'), context=action_context, init=init)
198
+ return JsonResponse({'result': _to_dict(response.response)})
199
+ except Exception as e:
200
+ return _error_response(500, _unwrap_cause(e))
201
+
202
+ return handler
203
+
204
+ return decorator
File without changes
@@ -0,0 +1,15 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,45 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Pytest configuration for the Django plugin tests.
18
+
19
+ Configures the minimum Django settings the plugin's tests need. Django's
20
+ ``HttpRequest``, ``StreamingHttpResponse``, and ``AsyncClient`` all require a
21
+ configured settings module before they can be imported or used.
22
+ """
23
+
24
+ import django
25
+ from django.conf import settings
26
+
27
+
28
+ def pytest_configure() -> None:
29
+ """Configure Django before any test imports run."""
30
+ if not settings.configured:
31
+ settings.configure(
32
+ DEBUG=True,
33
+ DATABASES={},
34
+ INSTALLED_APPS=['django.contrib.contenttypes', 'django.contrib.auth'],
35
+ ROOT_URLCONF=__name__,
36
+ SECRET_KEY='test-secret-key',
37
+ ALLOWED_HOSTS=['*'],
38
+ DEFAULT_CHARSET='utf-8',
39
+ USE_TZ=True,
40
+ )
41
+ django.setup()
42
+
43
+
44
+ # Required by Django; tests build their own urlpatterns via override_settings.
45
+ urlpatterns: list = []
@@ -0,0 +1,62 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Tests for Django plugin module exports and integration types."""
18
+
19
+ from genkit_django.handler import RequestData
20
+
21
+
22
+ class TestDjangoModuleExports:
23
+ """Tests for Django plugin module-level exports."""
24
+
25
+ def test_handler_module_importable(self) -> None:
26
+ """Test Handler module importable."""
27
+ from genkit_django import handler
28
+
29
+ assert hasattr(handler, 'genkit_django_handler')
30
+
31
+ def test_genkit_django_handler_signature(self) -> None:
32
+ """Test Genkit django handler signature."""
33
+ import inspect
34
+
35
+ from genkit_django.handler import genkit_django_handler
36
+
37
+ sig = inspect.signature(genkit_django_handler)
38
+ params = list(sig.parameters.keys())
39
+ assert 'ai' in params
40
+ assert 'context_provider' in params
41
+
42
+ def test_package_name(self) -> None:
43
+ """Package exports its fully qualified module name."""
44
+ from genkit_django import package_name
45
+
46
+ assert package_name() == 'genkit_django'
47
+
48
+
49
+ class TestRequestDataBase:
50
+ """Tests for the RequestData base class used by _DjangoRequestData."""
51
+
52
+ def test_request_data_is_importable(self) -> None:
53
+ """Test Request data is importable."""
54
+ assert RequestData is not None
55
+
56
+ def test_request_data_is_a_class(self) -> None:
57
+ """Test Request data is a class."""
58
+ assert isinstance(RequestData, type)
59
+
60
+ def test_request_data_has_init(self) -> None:
61
+ """Test Request data has init."""
62
+ assert hasattr(RequestData, '__init__')
@@ -0,0 +1,73 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Tests for Django handler decorator validation."""
18
+
19
+ import pytest
20
+ from genkit_django.handler import genkit_django_handler
21
+
22
+ from genkit._core._error import GenkitError
23
+
24
+
25
+ class TestGenkitDjangoHandlerValidation:
26
+ """Tests that genkit_django_handler rejects non-flow inputs."""
27
+
28
+ def test_rejects_plain_function(self) -> None:
29
+ """The decorator must reject arguments that are not Flow."""
30
+
31
+ class FakeGenkit:
32
+ pass
33
+
34
+ handler = genkit_django_handler(FakeGenkit()) # type: ignore[arg-type]
35
+ with pytest.raises(GenkitError, match='must apply @genkit_django_handler on a @flow'):
36
+ handler(lambda: None) # type: ignore[arg-type]
37
+
38
+ def test_rejects_string(self) -> None:
39
+ """Test Rejects string."""
40
+
41
+ class FakeGenkit:
42
+ pass
43
+
44
+ handler = genkit_django_handler(FakeGenkit()) # type: ignore[arg-type]
45
+ with pytest.raises(GenkitError, match='must apply @genkit_django_handler on a @flow'):
46
+ handler('not a flow') # type: ignore[arg-type]
47
+
48
+ def test_rejects_none(self) -> None:
49
+ """Test Rejects none."""
50
+
51
+ class FakeGenkit:
52
+ pass
53
+
54
+ handler = genkit_django_handler(FakeGenkit()) # type: ignore[arg-type]
55
+ with pytest.raises(GenkitError, match='must apply @genkit_django_handler on a @flow'):
56
+ handler(None) # type: ignore[arg-type]
57
+
58
+
59
+ class TestDjangoHandlerImports:
60
+ """Tests that module-level exports are correct."""
61
+
62
+ def test_genkit_django_handler_is_callable(self) -> None:
63
+ """Test Genkit django handler is callable."""
64
+ assert callable(genkit_django_handler)
65
+
66
+ def test_handler_accepts_context_provider(self) -> None:
67
+ """genkit_django_handler can be called with optional context_provider."""
68
+
69
+ class FakeGenkit:
70
+ pass
71
+
72
+ handler = genkit_django_handler(FakeGenkit(), context_provider=None) # type: ignore[arg-type]
73
+ assert callable(handler)
@@ -0,0 +1,174 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Tests for the Django plugin."""
19
+
20
+ import json
21
+ import sys
22
+ import types
23
+ from collections.abc import Iterator, Mapping
24
+ from typing import Any, cast
25
+
26
+ import pytest
27
+ from django.http import HttpRequest
28
+ from django.test import AsyncClient
29
+ from django.test.utils import override_settings
30
+ from django.urls import path
31
+ from genkit_django import genkit_django_handler
32
+
33
+ from genkit import ActionRunContext, Genkit
34
+ from genkit.plugin_api import RequestData
35
+
36
+
37
+ def _assert_is_error_response(parsed: dict) -> None:
38
+ """Assert parsed dict has HttpErrorWireFormat shape (message, status, details)."""
39
+ assert isinstance(parsed, dict)
40
+ assert all(k in parsed for k in ('message', 'status', 'details'))
41
+
42
+
43
+ def _build_views() -> dict[str, Any]:
44
+ """Build the Django views used by the integration tests."""
45
+ ai = Genkit()
46
+
47
+ async def my_context_provider(request_data: RequestData[HttpRequest]) -> dict[str, Any]:
48
+ """Provide a context for the flow."""
49
+ headers = cast(Mapping[str, str], request_data.request.headers)
50
+ return {'username': headers.get('authorization')}
51
+
52
+ @genkit_django_handler(ai, context_provider=my_context_provider)
53
+ @ai.flow()
54
+ async def say_hi(name: str, ctx: ActionRunContext) -> dict[str, str]:
55
+ ctx.send_chunk(1)
56
+ ctx.send_chunk({'username': ctx.context.get('username')})
57
+ ctx.send_chunk({'foo': 'bar'})
58
+ return {'bar': 'baz'}
59
+
60
+ @genkit_django_handler(ai)
61
+ @ai.flow()
62
+ async def raise_error(_: str) -> None:
63
+ raise ValueError('Intentional test error')
64
+
65
+ return {'say_hi': say_hi, 'raise_error': raise_error}
66
+
67
+
68
+ @pytest.fixture
69
+ def urlconf(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
70
+ """Install a temporary URLconf module that mounts the test views."""
71
+ views = _build_views()
72
+
73
+ module = types.ModuleType('genkit_django_tests_urls')
74
+ # Django reads urlpatterns off the module object; type checkers can't see
75
+ # this attribute on `types.ModuleType`, hence the suppressions.
76
+ module.urlpatterns = [ # type: ignore[attr-defined] # pyrefly: ignore[missing-attribute]
77
+ path('chat', views['say_hi']),
78
+ path('error_flow', views['raise_error']),
79
+ ]
80
+ monkeypatch.setitem(sys.modules, 'genkit_django_tests_urls', module)
81
+
82
+ with override_settings(ROOT_URLCONF='genkit_django_tests_urls'):
83
+ yield
84
+
85
+
86
+ @pytest.mark.asyncio
87
+ async def test_simple_post(urlconf: None) -> None: # noqa: ARG001
88
+ """A POST with the {data: ...} envelope returns {result: ...}."""
89
+ client = AsyncClient()
90
+ response = await client.post(
91
+ '/chat',
92
+ data=json.dumps({'data': 'banana'}),
93
+ content_type='application/json',
94
+ headers={'authorization': 'Pavel'},
95
+ )
96
+
97
+ assert response.status_code == 200
98
+ assert json.loads(response.content) == {'result': {'bar': 'baz'}}
99
+
100
+
101
+ @pytest.mark.asyncio
102
+ async def test_streaming(urlconf: None) -> None: # noqa: ARG001
103
+ """A POST with Accept: text/event-stream streams chunks then result."""
104
+ client = AsyncClient()
105
+ response = await client.post(
106
+ '/chat',
107
+ data=json.dumps({'data': 'banana'}),
108
+ content_type='application/json',
109
+ headers={
110
+ 'authorization': 'Pavel',
111
+ 'accept': 'text/event-stream',
112
+ },
113
+ )
114
+
115
+ assert response.status_code == 200
116
+ assert response['Content-Type'].startswith('text/event-stream')
117
+
118
+ chunks = [chunk async for chunk in response.streaming_content]
119
+
120
+ assert chunks == [
121
+ b'data: {"message":1}\n\n',
122
+ b'data: {"message":{"username":"Pavel"}}\n\n',
123
+ b'data: {"message":{"foo":"bar"}}\n\n',
124
+ b'data: {"result":{"bar":"baz"}}\n\n',
125
+ ]
126
+
127
+
128
+ @pytest.mark.asyncio
129
+ async def test_400_missing_data_returns_valid_json(urlconf: None) -> None: # noqa: ARG001
130
+ """400 (missing data) must return valid JSON."""
131
+ client = AsyncClient()
132
+ response = await client.post(
133
+ '/chat',
134
+ data=json.dumps({}), # no 'data' key
135
+ content_type='application/json',
136
+ )
137
+ assert response.status_code == 400
138
+ _assert_is_error_response(json.loads(response.content))
139
+
140
+
141
+ @pytest.mark.asyncio
142
+ async def test_400_invalid_json_returns_valid_json(urlconf: None) -> None: # noqa: ARG001
143
+ """400 (malformed body) must return valid JSON, not crash."""
144
+ client = AsyncClient()
145
+ response = await client.post(
146
+ '/chat',
147
+ data='not json',
148
+ content_type='application/json',
149
+ )
150
+ assert response.status_code == 400
151
+ _assert_is_error_response(json.loads(response.content))
152
+
153
+
154
+ @pytest.mark.asyncio
155
+ async def test_405_non_post_returns_valid_json(urlconf: None) -> None: # noqa: ARG001
156
+ """GET (or any non-POST) must return 405 with valid JSON, not a Django default."""
157
+ client = AsyncClient()
158
+ response = await client.get('/chat')
159
+ assert response.status_code == 405
160
+ _assert_is_error_response(json.loads(response.content))
161
+
162
+
163
+ @pytest.mark.asyncio
164
+ async def test_500_flow_exception_returns_valid_json(urlconf: None) -> None: # noqa: ARG001
165
+ """500 (flow exception) must return valid JSON in HttpErrorWireFormat shape."""
166
+ client = AsyncClient()
167
+ code_snippet = 'query = f"SELECT * FROM users WHERE id={user_input}"'
168
+ response = await client.post(
169
+ '/error_flow',
170
+ data=json.dumps({'data': code_snippet}),
171
+ content_type='application/json',
172
+ )
173
+ assert response.status_code == 500
174
+ _assert_is_error_response(json.loads(response.content))