django-ai-core 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.
- django_ai_core-0.1.0/LICENSE +27 -0
- django_ai_core-0.1.0/PKG-INFO +47 -0
- django_ai_core-0.1.0/README.md +22 -0
- django_ai_core-0.1.0/pyproject.toml +95 -0
- django_ai_core-0.1.0/src/django_ai_core/__init__.py +5 -0
- django_ai_core-0.1.0/src/django_ai_core/apps.py +8 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/agents/__init__.py +3 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/agents/base.py +100 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/agents/permissions.py +136 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/agents/urls.py +33 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/agents/views.py +104 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/__init__.py +39 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/apps.py +7 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/base.py +129 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/chunking.py +118 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/embedding.py +74 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/embedding_cache.py +208 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/management/__init__.py +0 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/management/commands/__init__.py +0 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/management/commands/rebuild_indexes.py +138 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/migrations/0001_initial.py +134 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/migrations/__init__.py +0 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/models.py +241 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/query.py +111 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/schema.py +42 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/signals.py +30 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/source.py +248 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/__init__.py +6 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/base.py +107 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/inmemory.py +60 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/llamaindex.py +97 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/__init__.py +3 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/apps.py +6 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/migrations/0001_initial.py +33 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/migrations/__init__.py +0 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/models.py +24 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/pgvector/provider.py +151 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/qdrant.py +102 -0
- django_ai_core-0.1.0/src/django_ai_core/contrib/index/storage/s3vectors.py +134 -0
- django_ai_core-0.1.0/src/django_ai_core/llm/__init__.py +3 -0
- django_ai_core-0.1.0/src/django_ai_core/llm/base.py +30 -0
- django_ai_core-0.1.0/src/django_ai_core/llm/prompt.py +48 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright (c) 2014-present Torchbox Ltd and individual contributors.
|
|
2
|
+
All rights reserved.
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without modification,
|
|
5
|
+
are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
8
|
+
this list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
* Redistributions in binary form must reproduce the above copyright
|
|
11
|
+
notice, this list of conditions and the following disclaimer in the
|
|
12
|
+
documentation and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
* Neither the name of Torchbox nor the names of its contributors may be used
|
|
15
|
+
to endorse or promote products derived from this software without
|
|
16
|
+
specific prior written permission.
|
|
17
|
+
|
|
18
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
19
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
20
|
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
|
22
|
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
23
|
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
24
|
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
25
|
+
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
27
|
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django-ai-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Django AI Core provides developer-focused AI features for implementing AI tooling in to Django sites.
|
|
5
|
+
Author: Wagtail core team + contributors
|
|
6
|
+
Author-email: Wagtail core team + contributors <hello@wagtail.org>
|
|
7
|
+
License-Expression: BSD-3-Clause
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Web Environment
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Framework :: Django
|
|
19
|
+
Classifier: Framework :: Django :: 5.2
|
|
20
|
+
Classifier: Framework :: Django :: 6.0
|
|
21
|
+
Requires-Dist: any-llm-sdk==0.20.3
|
|
22
|
+
Requires-Dist: queryish>=0.2.0
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Django AI Core
|
|
27
|
+
|
|
28
|
+
**Developer-focused package for implementing AI tooling into Django sites.**
|
|
29
|
+
|
|
30
|
+
Django AI Core provides core functionality for interacting with LLMs in your Django project, as well as optional modules for building AI-powered apps.
|
|
31
|
+
|
|
32
|
+
## TODO
|
|
33
|
+
|
|
34
|
+
- Core:
|
|
35
|
+
- Logging for LLM requests
|
|
36
|
+
- Async/streaming support
|
|
37
|
+
- Agents:
|
|
38
|
+
- Rate limiting
|
|
39
|
+
- Streaming responses
|
|
40
|
+
- Index:
|
|
41
|
+
- Test different backends
|
|
42
|
+
- Docs
|
|
43
|
+
- Higher-level API?
|
|
44
|
+
- Chat:
|
|
45
|
+
- Build Chat/RAG module with chat UI
|
|
46
|
+
- MCP:
|
|
47
|
+
- Build MCP 'function' registry
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Django AI Core
|
|
2
|
+
|
|
3
|
+
**Developer-focused package for implementing AI tooling into Django sites.**
|
|
4
|
+
|
|
5
|
+
Django AI Core provides core functionality for interacting with LLMs in your Django project, as well as optional modules for building AI-powered apps.
|
|
6
|
+
|
|
7
|
+
## TODO
|
|
8
|
+
|
|
9
|
+
- Core:
|
|
10
|
+
- Logging for LLM requests
|
|
11
|
+
- Async/streaming support
|
|
12
|
+
- Agents:
|
|
13
|
+
- Rate limiting
|
|
14
|
+
- Streaming responses
|
|
15
|
+
- Index:
|
|
16
|
+
- Test different backends
|
|
17
|
+
- Docs
|
|
18
|
+
- Higher-level API?
|
|
19
|
+
- Chat:
|
|
20
|
+
- Build Chat/RAG module with chat UI
|
|
21
|
+
- MCP:
|
|
22
|
+
- Build MCP 'function' registry
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "django-ai-core"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Django AI Core provides developer-focused AI features for implementing AI tooling in to Django sites."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "BSD-3-Clause"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Wagtail core team + contributors", email = "hello@wagtail.org" },
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"any-llm-sdk==0.20.3",
|
|
14
|
+
"queryish>=0.2.0",
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Environment :: Web Environment",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
"Framework :: Django",
|
|
27
|
+
"Framework :: Django :: 5.2",
|
|
28
|
+
"Framework :: Django :: 6.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = [
|
|
33
|
+
"django>=5.2.3",
|
|
34
|
+
"django-stubs>=5.2.5",
|
|
35
|
+
"mkdocs>=1.6.1",
|
|
36
|
+
"mkdocs-awesome-nav>=3.2.0",
|
|
37
|
+
"mkdocs-material>=9.6.20",
|
|
38
|
+
"prek>=0.2.2",
|
|
39
|
+
]
|
|
40
|
+
test = [
|
|
41
|
+
"psycopg[binary]>=3.2.10",
|
|
42
|
+
"pgvector>=0.4.1",
|
|
43
|
+
"pytest-django>=4.11.1",
|
|
44
|
+
"coverage>=7.10.7",
|
|
45
|
+
"pytest>=8.4.1",
|
|
46
|
+
"dj-database-url>=3.0.1",
|
|
47
|
+
"pytest-cov>=7.0.0",
|
|
48
|
+
"tox>=4.30.2",
|
|
49
|
+
"tox-gh-actions>=3.3.0",
|
|
50
|
+
"tox-uv>=1.28.0",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[build-system]
|
|
54
|
+
requires = ["uv_build>=0.8.22,<0.9.0"]
|
|
55
|
+
build-backend = "uv_build"
|
|
56
|
+
|
|
57
|
+
[tool.uv]
|
|
58
|
+
default-groups = ["dev", "test"]
|
|
59
|
+
|
|
60
|
+
[tool.pytest.ini_options]
|
|
61
|
+
DJANGO_SETTINGS_MODULE = "testapp.settings"
|
|
62
|
+
pythonpath = ["./src", "./tests"]
|
|
63
|
+
log_level = "INFO"
|
|
64
|
+
filterwarnings = [
|
|
65
|
+
"ignore::DeprecationWarning",
|
|
66
|
+
]
|
|
67
|
+
addopts = [
|
|
68
|
+
"-v",
|
|
69
|
+
"--tb=short",
|
|
70
|
+
"--strict-markers",
|
|
71
|
+
"--disable-warnings"
|
|
72
|
+
]
|
|
73
|
+
markers = [
|
|
74
|
+
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
75
|
+
"integration: marks tests as integration tests",
|
|
76
|
+
"unit: marks tests as unit tests",
|
|
77
|
+
"asyncio: marks tests as async"
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
[tool.coverage.run]
|
|
81
|
+
branch = true
|
|
82
|
+
source = ["src/django_ai_core"]
|
|
83
|
+
omit = ["*/migrations/*", "*/tests/*"]
|
|
84
|
+
|
|
85
|
+
[tool.coverage.report]
|
|
86
|
+
exclude_lines = [
|
|
87
|
+
'pragma: no cover',
|
|
88
|
+
'def __repr__',
|
|
89
|
+
'if self\.debug',
|
|
90
|
+
'raise AssertionError',
|
|
91
|
+
'raise NotImplementedError',
|
|
92
|
+
'if 0:',
|
|
93
|
+
'if __name__ == .__main__.:'
|
|
94
|
+
]
|
|
95
|
+
ignore_errors = true
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import get_args, get_origin, Annotated
|
|
5
|
+
|
|
6
|
+
from django.core.validators import validate_slug
|
|
7
|
+
from django.core.exceptions import ValidationError
|
|
8
|
+
|
|
9
|
+
from .permissions import BasePermission
|
|
10
|
+
from .views import AgentExecutionView
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class AgentParameter:
|
|
15
|
+
name: str
|
|
16
|
+
type: type
|
|
17
|
+
description: str
|
|
18
|
+
permission = BasePermission | None
|
|
19
|
+
|
|
20
|
+
def as_dict(self):
|
|
21
|
+
return {
|
|
22
|
+
"name": self.name,
|
|
23
|
+
"type": self.type.__name__,
|
|
24
|
+
"description": self.description,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Agent(ABC):
|
|
29
|
+
"""Base class for agents."""
|
|
30
|
+
|
|
31
|
+
slug: str
|
|
32
|
+
description: str
|
|
33
|
+
parameters: list[AgentParameter] | None
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def as_view(cls):
|
|
37
|
+
return AgentExecutionView.as_view(agent_slug=cls.slug)
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def _derive_parameters_from_signature(cls) -> list[AgentParameter]:
|
|
41
|
+
"""Derive parameters from `execute` type signature"""
|
|
42
|
+
parameters = []
|
|
43
|
+
annotations = inspect.get_annotations(cls.execute)
|
|
44
|
+
for name, annotation in annotations.items():
|
|
45
|
+
if name == "return":
|
|
46
|
+
continue
|
|
47
|
+
description: str = ""
|
|
48
|
+
base_type = annotation
|
|
49
|
+
if get_origin(annotation) is Annotated:
|
|
50
|
+
base_type, *metadata = get_args(annotation)
|
|
51
|
+
if metadata and isinstance(metadata[0], str):
|
|
52
|
+
description = metadata[0]
|
|
53
|
+
parameters.append(
|
|
54
|
+
AgentParameter(name=name, type=base_type, description=description)
|
|
55
|
+
)
|
|
56
|
+
return parameters
|
|
57
|
+
|
|
58
|
+
@abstractmethod
|
|
59
|
+
def execute(self, *args, **kwargs) -> str | dict | list:
|
|
60
|
+
"""Execute the agent"""
|
|
61
|
+
|
|
62
|
+
def __init_subclass__(cls, **kwargs):
|
|
63
|
+
super().__init_subclass__(**kwargs)
|
|
64
|
+
|
|
65
|
+
if "parameters" not in cls.__dict__:
|
|
66
|
+
cls.parameters = cls._derive_parameters_from_signature()
|
|
67
|
+
|
|
68
|
+
if hasattr(cls, "slug"):
|
|
69
|
+
try:
|
|
70
|
+
validate_slug(cls.slug)
|
|
71
|
+
except ValidationError:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"Agent {cls.__name__} has an invalid slug: {cls.slug}. Use a valid “slug” consisting of letters, numbers, underscores or hyphens."
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AgentRegistry:
|
|
78
|
+
def __init__(self):
|
|
79
|
+
self._agents: dict[str, type[Agent]] = {}
|
|
80
|
+
|
|
81
|
+
def register(self):
|
|
82
|
+
"""Decorator to register an agent."""
|
|
83
|
+
|
|
84
|
+
def decorator(cls: type[Agent]) -> type[Agent]:
|
|
85
|
+
agent_slug = getattr(cls, "slug")
|
|
86
|
+
self._agents[agent_slug] = cls
|
|
87
|
+
return cls
|
|
88
|
+
|
|
89
|
+
return decorator
|
|
90
|
+
|
|
91
|
+
def get(self, slug: str) -> type[Agent]:
|
|
92
|
+
if slug not in self._agents:
|
|
93
|
+
raise KeyError(f"Agent '{slug}' not found")
|
|
94
|
+
return self._agents[slug]
|
|
95
|
+
|
|
96
|
+
def list(self) -> dict[str, type[Agent]]:
|
|
97
|
+
return self._agents.copy()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
registry = AgentRegistry()
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
from django.contrib.auth.models import AnonymousUser
|
|
4
|
+
from django.http import HttpRequest
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BasePermission(ABC):
|
|
8
|
+
"""
|
|
9
|
+
Base class for implementing custom permission checks on agents.
|
|
10
|
+
|
|
11
|
+
Subclass this to create your own permission logic for controlling
|
|
12
|
+
who can execute agents in your application.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def has_permission(self, request: HttpRequest, agent_slug: str, **kwargs) -> bool:
|
|
17
|
+
"""
|
|
18
|
+
Check if the request has permission to execute the agent.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
request: The Django HTTP request object
|
|
22
|
+
agent_slug: The slug of the agent being executed
|
|
23
|
+
**kwargs: Additional context that may be useful for permission checks
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
bool: True if permission is granted, False otherwise
|
|
27
|
+
"""
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
def get_permission_denied_message(
|
|
31
|
+
self, request: HttpRequest, agent_slug: str
|
|
32
|
+
) -> str:
|
|
33
|
+
"""
|
|
34
|
+
Return a custom message when permission is denied.
|
|
35
|
+
|
|
36
|
+
Override this method to provide specific error messages.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
request: The Django HTTP request object
|
|
40
|
+
agent_slug: The slug of the agent being executed
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
str: The permission denied message
|
|
44
|
+
"""
|
|
45
|
+
return f"You do not have permission to execute agent '{agent_slug}'"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AllowAny(BasePermission):
|
|
49
|
+
"""
|
|
50
|
+
Permission that allows all requests.
|
|
51
|
+
|
|
52
|
+
This is the default behavior if no permission is specified.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def has_permission(self, request: HttpRequest, agent_slug: str, **kwargs) -> bool:
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class IsAuthenticated(BasePermission):
|
|
60
|
+
"""
|
|
61
|
+
Permission that requires the user to be authenticated.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def has_permission(self, request: HttpRequest, agent_slug: str, **kwargs) -> bool:
|
|
65
|
+
return bool(request.user and request.user.is_authenticated)
|
|
66
|
+
|
|
67
|
+
def get_permission_denied_message(
|
|
68
|
+
self, request: HttpRequest, agent_slug: str
|
|
69
|
+
) -> str:
|
|
70
|
+
return "Authentication required to execute this agent"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class DjangoPermission(BasePermission):
|
|
74
|
+
"""
|
|
75
|
+
Permission that uses Django's built-in permission system.
|
|
76
|
+
|
|
77
|
+
This checks for a specific Django permission before allowing agent execution.
|
|
78
|
+
The permission should be in the format 'app_label.permission_codename'.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
permission: The Django permission string (e.g., 'myapp.can_use_agent')
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(self, permission: str):
|
|
85
|
+
if "." not in permission:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
"Permission must be in format 'app_label.permission_codename', "
|
|
88
|
+
f"got '{permission}'"
|
|
89
|
+
)
|
|
90
|
+
self.permission = permission
|
|
91
|
+
|
|
92
|
+
def has_permission(self, request: HttpRequest, agent_slug: str, **kwargs) -> bool:
|
|
93
|
+
if not request.user or isinstance(request.user, AnonymousUser):
|
|
94
|
+
return False
|
|
95
|
+
return request.user.has_perm(self.permission)
|
|
96
|
+
|
|
97
|
+
def get_permission_denied_message(
|
|
98
|
+
self, request: HttpRequest, agent_slug: str
|
|
99
|
+
) -> str:
|
|
100
|
+
return f"You do not have the required permission '{self.permission}' to execute agent '{agent_slug}'"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CompositePermission(BasePermission):
|
|
104
|
+
"""
|
|
105
|
+
Permission that combines multiple permissions
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
permissions: List of permissions
|
|
109
|
+
require_all: If True, all permissions must pass. If False, any permission can pass.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
def __init__(self, permissions: list[BasePermission], require_all: bool = True):
|
|
113
|
+
if not permissions:
|
|
114
|
+
raise ValueError("At least one permission must be provided")
|
|
115
|
+
self.permissions = permissions
|
|
116
|
+
self.require_all = require_all
|
|
117
|
+
|
|
118
|
+
def has_permission(self, request: HttpRequest, agent_slug: str, **kwargs) -> bool:
|
|
119
|
+
if self.require_all:
|
|
120
|
+
return all(
|
|
121
|
+
permission.has_permission(request, agent_slug, **kwargs)
|
|
122
|
+
for permission in self.permissions
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
return any(
|
|
126
|
+
permission.has_permission(request, agent_slug, **kwargs)
|
|
127
|
+
for permission in self.permissions
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def get_permission_denied_message(
|
|
131
|
+
self, request: HttpRequest, agent_slug: str
|
|
132
|
+
) -> str:
|
|
133
|
+
for permission in self.permissions:
|
|
134
|
+
if not permission.has_permission(request, agent_slug):
|
|
135
|
+
return permission.get_permission_denied_message(request, agent_slug)
|
|
136
|
+
return f"You do not have permission to execute agent '{agent_slug}'"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from django.urls import path
|
|
2
|
+
|
|
3
|
+
from . import registry
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def agent_urls() -> list:
|
|
7
|
+
"""
|
|
8
|
+
Generate URL patterns for all registered agents.
|
|
9
|
+
|
|
10
|
+
Returns:
|
|
11
|
+
List of URL patterns
|
|
12
|
+
|
|
13
|
+
Example:
|
|
14
|
+
# In your main urls.py
|
|
15
|
+
from django_ai_core.agent import generate_agent_urls
|
|
16
|
+
|
|
17
|
+
urlpatterns = [
|
|
18
|
+
# ... your other URLs
|
|
19
|
+
path('ai/', include(generate_agent_urls())),
|
|
20
|
+
]
|
|
21
|
+
"""
|
|
22
|
+
urlpatterns = []
|
|
23
|
+
|
|
24
|
+
for agent in registry.list().values():
|
|
25
|
+
urlpatterns.append(
|
|
26
|
+
path(
|
|
27
|
+
f"{agent.slug}/",
|
|
28
|
+
agent.as_view(),
|
|
29
|
+
name=f"agent_{agent.slug}",
|
|
30
|
+
)
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
return urlpatterns
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
from typing import Any, TYPE_CHECKING
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from django.http import JsonResponse
|
|
5
|
+
from django.views import View
|
|
6
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
7
|
+
from django.utils.decorators import method_decorator
|
|
8
|
+
|
|
9
|
+
from .permissions import AllowAny
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from . import Agent
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AgentExecutionException(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AgentNotFound(AgentExecutionException):
|
|
20
|
+
code = "agent_not_found"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@method_decorator(csrf_exempt, name="dispatch")
|
|
24
|
+
class AgentExecutionView(View):
|
|
25
|
+
agent_slug: str = ""
|
|
26
|
+
|
|
27
|
+
def get(self, request):
|
|
28
|
+
try:
|
|
29
|
+
agent = self._get_agent()
|
|
30
|
+
except AgentNotFound as e:
|
|
31
|
+
return JsonResponse(
|
|
32
|
+
{
|
|
33
|
+
"error": f"Agent not found: {self.agent_slug}",
|
|
34
|
+
"code": e.code,
|
|
35
|
+
},
|
|
36
|
+
status=404,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
return JsonResponse(
|
|
40
|
+
{
|
|
41
|
+
"slug": agent.slug,
|
|
42
|
+
"description": agent.description,
|
|
43
|
+
"parameters": [param.as_dict() for param in agent.parameters or []],
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def post(self, request):
|
|
48
|
+
"""
|
|
49
|
+
Execute the agent with provided input data.
|
|
50
|
+
|
|
51
|
+
Expected JSON payload:
|
|
52
|
+
{
|
|
53
|
+
"arguments": {
|
|
54
|
+
"foo": "bar"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
data = json.loads(request.body)
|
|
60
|
+
except json.JSONDecodeError:
|
|
61
|
+
return JsonResponse({"error": "Invalid JSON in request body"}, status=400)
|
|
62
|
+
|
|
63
|
+
if "arguments" not in data:
|
|
64
|
+
return JsonResponse(
|
|
65
|
+
{"error": "Missing required field: arguments"}, status=400
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
agent = self._get_agent()
|
|
70
|
+
except AgentNotFound as e:
|
|
71
|
+
return JsonResponse(
|
|
72
|
+
{
|
|
73
|
+
"error": f"Agent not found: {self.agent_slug}",
|
|
74
|
+
"code": e.code,
|
|
75
|
+
},
|
|
76
|
+
status=404,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
permission = getattr(agent, "permission", None) or AllowAny()
|
|
80
|
+
if not permission.has_permission(request, self.agent_slug):
|
|
81
|
+
return JsonResponse(
|
|
82
|
+
{
|
|
83
|
+
"error": permission.get_permission_denied_message(
|
|
84
|
+
request, self.agent_slug
|
|
85
|
+
),
|
|
86
|
+
"code": "permission_denied",
|
|
87
|
+
},
|
|
88
|
+
status=403,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
result = self._execute_agent(agent, data["arguments"])
|
|
92
|
+
|
|
93
|
+
return JsonResponse({"status": "completed", "data": result})
|
|
94
|
+
|
|
95
|
+
def _get_agent(self) -> "Agent":
|
|
96
|
+
from . import registry
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
return registry.get(self.agent_slug)()
|
|
100
|
+
except KeyError:
|
|
101
|
+
raise AgentNotFound
|
|
102
|
+
|
|
103
|
+
def _execute_agent(self, agent: "Agent", arguments: dict[str, Any]) -> Any:
|
|
104
|
+
return agent.execute(**arguments)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from .base import (
|
|
2
|
+
VectorIndex,
|
|
3
|
+
IndexRegistry,
|
|
4
|
+
registry,
|
|
5
|
+
)
|
|
6
|
+
from .chunking import (
|
|
7
|
+
ChunkTransformer,
|
|
8
|
+
SimpleChunkTransformer,
|
|
9
|
+
SentenceChunkTransformer,
|
|
10
|
+
ParagraphChunkTransformer,
|
|
11
|
+
)
|
|
12
|
+
from .embedding import (
|
|
13
|
+
CoreEmbeddingTransformer,
|
|
14
|
+
)
|
|
15
|
+
from .embedding_cache import (
|
|
16
|
+
CachedEmbeddingTransformer,
|
|
17
|
+
)
|
|
18
|
+
from .source import (
|
|
19
|
+
ModelSource,
|
|
20
|
+
)
|
|
21
|
+
from .storage import (
|
|
22
|
+
StorageProvider,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"ChunkTransformer",
|
|
28
|
+
"ModelSource",
|
|
29
|
+
"IndexRegistry",
|
|
30
|
+
"ParagraphChunkTransformer",
|
|
31
|
+
"SentenceChunkTransformer",
|
|
32
|
+
"SimpleChunkTransformer",
|
|
33
|
+
"CoreEmbeddingTransformer",
|
|
34
|
+
"CachedEmbeddingTransformer",
|
|
35
|
+
"StorageProvider",
|
|
36
|
+
"VectorIndex",
|
|
37
|
+
"ModelSource",
|
|
38
|
+
"registry",
|
|
39
|
+
]
|