zerodb-fastapi 0.1.0__py3-none-any.whl

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.
tests/__init__.py ADDED
File without changes
@@ -0,0 +1,90 @@
1
+ """Tests for zerodb-fastapi package. Refs #2458."""
2
+
3
+ import pytest
4
+ from unittest.mock import AsyncMock, MagicMock, patch
5
+ from zerodb_fastapi import ZeroDBClient, ZeroDBMiddleware, get_zerodb, ZeroDBRouter
6
+ from zerodb_fastapi.router import RememberRequest, RecallRequest
7
+
8
+
9
+ class TestZeroDBClient:
10
+ def test_client_init(self):
11
+ client = ZeroDBClient(api_key="test", project_id="proj-1")
12
+ assert client.project_id == "proj-1"
13
+
14
+ @pytest.mark.asyncio
15
+ async def test_health(self):
16
+ client = ZeroDBClient(api_key="k", project_id="p")
17
+ client._client = AsyncMock()
18
+ client._client.get.return_value = MagicMock(
19
+ status_code=200, json=lambda: {"status": "ok"})
20
+ client._client.get.return_value.raise_for_status = MagicMock()
21
+ result = await client.health()
22
+ assert result["status"] == "ok"
23
+
24
+ @pytest.mark.asyncio
25
+ async def test_search_calls_semantic_search_endpoint_with_limit_not_top_k(self):
26
+ # /api/v1/public/vectors/search doesn't exist (confirmed against the
27
+ # live OpenAPI spec) -- the real text-query search endpoint is
28
+ # embeddings/semantic-search, and it takes `limit`, not `top_k`.
29
+ client = ZeroDBClient(api_key="k", project_id="p")
30
+ client._client = AsyncMock()
31
+ client._client.post.return_value = MagicMock(
32
+ status_code=200, json=lambda: {"results": []})
33
+ client._client.post.return_value.raise_for_status = MagicMock()
34
+ await client.search("test query", top_k=7)
35
+ call_args = client._client.post.call_args
36
+ assert "/embeddings/semantic-search" in call_args[0][0]
37
+ assert call_args[1]["json"]["limit"] == 7
38
+ assert "top_k" not in call_args[1]["json"]
39
+
40
+
41
+ class TestRequestModels:
42
+ def test_remember_default_namespace_is_global_not_default(self):
43
+ # The real /memory/v2/remember endpoint rejects 'default' with a 422
44
+ # (confirmed live); only 'global', 'project:<id>', 'session:<id>' work.
45
+ req = RememberRequest(content="hello")
46
+ assert req.namespace == "global"
47
+
48
+ def test_recall_default_namespace_is_global_not_default(self):
49
+ # 'default' crashes /memory/v2/recall with an unhandled 500 (confirmed
50
+ # live) -- not just rejected cleanly, so this default is especially
51
+ # important to get right.
52
+ req = RecallRequest(query="hello")
53
+ assert req.namespace == "global"
54
+
55
+
56
+ class TestZeroDBRouter:
57
+ def test_router_has_routes(self):
58
+ # ZeroDBRouter takes no credentials -- those are injected via
59
+ # ZeroDBMiddleware into request.state, not held by the router
60
+ # itself (see get_zerodb()/Depends()). Routes live on the real
61
+ # APIRouter at .router, not directly on the ZeroDBRouter wrapper.
62
+ router = ZeroDBRouter(prefix="/zerodb")
63
+ paths = [r.path for r in router.router.routes]
64
+ assert "/zerodb/health" in paths
65
+ assert "/zerodb/remember" in paths
66
+ assert "/zerodb/recall" in paths
67
+ assert "/zerodb/search" in paths
68
+
69
+
70
+ class TestMiddleware:
71
+ def test_middleware_class_exists(self):
72
+ assert ZeroDBMiddleware is not None
73
+
74
+ def test_middleware_constructs_client_with_credentials(self):
75
+ app = MagicMock()
76
+ middleware = ZeroDBMiddleware(app, api_key="k", project_id="p")
77
+ assert middleware.client.api_key == "k"
78
+ assert middleware.client.project_id == "p"
79
+
80
+ @pytest.mark.asyncio
81
+ async def test_dispatch_injects_client_into_request_state(self):
82
+ app = MagicMock()
83
+ middleware = ZeroDBMiddleware(app, api_key="k", project_id="p")
84
+ request = MagicMock()
85
+ request.state = MagicMock()
86
+ call_next = AsyncMock(return_value=MagicMock())
87
+
88
+ await middleware.dispatch(request, call_next)
89
+
90
+ assert request.state.zerodb is middleware.client
@@ -0,0 +1,14 @@
1
+ """ZeroDB FastAPI integration — router, middleware, and DI helpers - Refs #1500"""
2
+
3
+ from zerodb_fastapi.dependencies import ZeroDBClient, get_memory, get_zerodb
4
+ from zerodb_fastapi.middleware import ZeroDBMiddleware
5
+ from zerodb_fastapi.router import ZeroDBRouter
6
+
7
+ __all__ = [
8
+ "ZeroDBClient",
9
+ "ZeroDBMiddleware",
10
+ "ZeroDBRouter",
11
+ "get_memory",
12
+ "get_zerodb",
13
+ ]
14
+ __version__ = "0.1.0"
@@ -0,0 +1,109 @@
1
+ """FastAPI dependency injection helpers for ZeroDB - Refs #1500"""
2
+
3
+ from typing import Optional
4
+
5
+ import httpx
6
+ from fastapi import Request
7
+
8
+
9
+ class ZeroDBClient:
10
+ """HTTP client wrapper for ZeroDB API."""
11
+
12
+ def __init__(
13
+ self,
14
+ api_key: str,
15
+ project_id: str,
16
+ base_url: str = "https://api.ainative.studio",
17
+ ):
18
+ self.api_key = api_key
19
+ self.project_id = project_id
20
+ self.base_url = base_url.rstrip("/")
21
+ self._client = httpx.AsyncClient(
22
+ base_url=self.base_url,
23
+ headers={"Authorization": f"Bearer {self.api_key}"},
24
+ timeout=30.0,
25
+ )
26
+
27
+ async def health(self) -> dict:
28
+ """Check ZeroDB API health."""
29
+ resp = await self._client.get("/health")
30
+ resp.raise_for_status()
31
+ return resp.json()
32
+
33
+ async def remember(self, content: str, namespace: str = "default", metadata: Optional[dict] = None) -> dict:
34
+ """Store a memory in ZeroDB."""
35
+ payload = {
36
+ "project_id": self.project_id,
37
+ "content": content,
38
+ "namespace": namespace,
39
+ }
40
+ if metadata:
41
+ payload["metadata"] = metadata
42
+ resp = await self._client.post("/api/v1/public/memory/v2/remember", json=payload)
43
+ resp.raise_for_status()
44
+ return resp.json()
45
+
46
+ async def recall(self, query: str, namespace: str = "default", top_k: int = 5) -> dict:
47
+ """Recall memories from ZeroDB."""
48
+ payload = {
49
+ "project_id": self.project_id,
50
+ "query": query,
51
+ "namespace": namespace,
52
+ "top_k": top_k,
53
+ }
54
+ resp = await self._client.post("/api/v1/public/memory/v2/recall", json=payload)
55
+ resp.raise_for_status()
56
+ return resp.json()
57
+
58
+ async def search(self, query: str, namespace: str = "default", top_k: int = 10) -> dict:
59
+ """Semantic search across stored vectors.
60
+
61
+ Was calling /api/v1/public/vectors/search with a text `query` field --
62
+ that path doesn't exist (confirmed against the live OpenAPI spec), and
63
+ the real vector-search endpoints take a raw `vector` array, not text.
64
+ The real text-query semantic search endpoint is
65
+ /api/v1/public/embeddings/semantic-search, which takes `limit` (not
66
+ `top_k`) and auto-embeds `query` server-side.
67
+ """
68
+ payload = {
69
+ "project_id": self.project_id,
70
+ "query": query,
71
+ "namespace": namespace,
72
+ "limit": top_k,
73
+ }
74
+ resp = await self._client.post("/api/v1/public/embeddings/semantic-search", json=payload)
75
+ resp.raise_for_status()
76
+ return resp.json()
77
+
78
+ async def close(self):
79
+ """Close the underlying HTTP client."""
80
+ await self._client.aclose()
81
+
82
+
83
+ def get_zerodb(request: Request) -> ZeroDBClient:
84
+ """FastAPI dependency that retrieves the ZeroDB client from request state.
85
+
86
+ Usage:
87
+ @app.get("/my-endpoint")
88
+ async def my_endpoint(zerodb: ZeroDBClient = Depends(get_zerodb)):
89
+ result = await zerodb.recall("hello")
90
+ return result
91
+ """
92
+ client = getattr(request.state, "zerodb", None)
93
+ if client is None:
94
+ raise RuntimeError(
95
+ "ZeroDB client not found in request.state. "
96
+ "Ensure ZeroDBMiddleware is added to your FastAPI app."
97
+ )
98
+ return client
99
+
100
+
101
+ def get_memory(request: Request) -> ZeroDBClient:
102
+ """Alias for get_zerodb() — convenience for memory-focused usage.
103
+
104
+ Usage:
105
+ @app.get("/recall")
106
+ async def recall(memory: ZeroDBClient = Depends(get_memory)):
107
+ return await memory.recall("search term")
108
+ """
109
+ return get_zerodb(request)
@@ -0,0 +1,40 @@
1
+ """FastAPI middleware that injects ZeroDB client into request.state - Refs #1500"""
2
+
3
+ from starlette.middleware.base import BaseHTTPMiddleware
4
+ from starlette.requests import Request
5
+ from starlette.responses import Response
6
+
7
+ from zerodb_fastapi.dependencies import ZeroDBClient
8
+
9
+
10
+ class ZeroDBMiddleware(BaseHTTPMiddleware):
11
+ """Middleware that attaches a ZeroDBClient to each request.
12
+
13
+ Usage:
14
+ app = FastAPI()
15
+ app.add_middleware(
16
+ ZeroDBMiddleware,
17
+ api_key="your-api-key",
18
+ project_id="your-project-id",
19
+ )
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ app,
25
+ api_key: str,
26
+ project_id: str,
27
+ base_url: str = "https://api.ainative.studio",
28
+ ):
29
+ super().__init__(app)
30
+ self.client = ZeroDBClient(
31
+ api_key=api_key,
32
+ project_id=project_id,
33
+ base_url=base_url,
34
+ )
35
+
36
+ async def dispatch(self, request: Request, call_next) -> Response:
37
+ """Inject zerodb client into request.state before processing."""
38
+ request.state.zerodb = self.client
39
+ response = await call_next(request)
40
+ return response
@@ -0,0 +1,91 @@
1
+ """Pre-wired FastAPI router with health, memory, and search endpoints - Refs #1500"""
2
+
3
+ from typing import Optional
4
+
5
+ from fastapi import APIRouter, Depends
6
+ from pydantic import BaseModel, Field
7
+
8
+ from zerodb_fastapi.dependencies import ZeroDBClient, get_zerodb
9
+
10
+
11
+ class RememberRequest(BaseModel):
12
+ """Request body for storing a memory."""
13
+ content: str = Field(..., description="Text content to remember")
14
+ # The real /memory/v2/remember and /recall endpoints only accept
15
+ # 'global', 'project:<id>', or 'session:<id>' -- 'default' is rejected
16
+ # with a 422 (remember) or crashes with a 500 (recall). Verified live.
17
+ namespace: str = Field(default="global", description="Memory namespace: 'global', 'project:<id>', or 'session:<id>'")
18
+ metadata: Optional[dict] = Field(default=None, description="Optional metadata")
19
+
20
+
21
+ class RecallRequest(BaseModel):
22
+ """Request body for recalling memories."""
23
+ query: str = Field(..., description="Search query")
24
+ namespace: str = Field(default="global", description="Memory namespace: 'global', 'project:<id>', or 'session:<id>'")
25
+ top_k: int = Field(default=5, ge=1, le=100, description="Number of results")
26
+
27
+
28
+ class SearchRequest(BaseModel):
29
+ """Request body for semantic search."""
30
+ query: str = Field(..., description="Search query")
31
+ namespace: str = Field(default="default", description="Memory namespace")
32
+ top_k: int = Field(default=10, ge=1, le=100, description="Number of results")
33
+
34
+
35
+ class ZeroDBRouter:
36
+ """Pre-configured FastAPI router with ZeroDB endpoints.
37
+
38
+ Usage:
39
+ from zerodb_fastapi import ZeroDBRouter
40
+
41
+ zerodb_router = ZeroDBRouter(prefix="/zerodb")
42
+ app.include_router(zerodb_router.router)
43
+ """
44
+
45
+ def __init__(self, prefix: str = "/zerodb", tags: Optional[list] = None):
46
+ self.router = APIRouter(prefix=prefix, tags=tags or ["zerodb"])
47
+ self._register_routes()
48
+
49
+ def _register_routes(self):
50
+ """Register all ZeroDB routes on the router."""
51
+
52
+ @self.router.get("/health")
53
+ async def health(zerodb: ZeroDBClient = Depends(get_zerodb)):
54
+ """Check ZeroDB API health."""
55
+ return await zerodb.health()
56
+
57
+ @self.router.post("/remember")
58
+ async def remember(
59
+ body: RememberRequest,
60
+ zerodb: ZeroDBClient = Depends(get_zerodb),
61
+ ):
62
+ """Store a memory in ZeroDB."""
63
+ return await zerodb.remember(
64
+ content=body.content,
65
+ namespace=body.namespace,
66
+ metadata=body.metadata,
67
+ )
68
+
69
+ @self.router.post("/recall")
70
+ async def recall(
71
+ body: RecallRequest,
72
+ zerodb: ZeroDBClient = Depends(get_zerodb),
73
+ ):
74
+ """Recall memories from ZeroDB."""
75
+ return await zerodb.recall(
76
+ query=body.query,
77
+ namespace=body.namespace,
78
+ top_k=body.top_k,
79
+ )
80
+
81
+ @self.router.post("/search")
82
+ async def search(
83
+ body: SearchRequest,
84
+ zerodb: ZeroDBClient = Depends(get_zerodb),
85
+ ):
86
+ """Semantic search across ZeroDB."""
87
+ return await zerodb.search(
88
+ query=body.query,
89
+ namespace=body.namespace,
90
+ top_k=body.top_k,
91
+ )
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: zerodb-fastapi
3
+ Version: 0.1.0
4
+ Summary: FastAPI integration for ZeroDB — middleware, dependencies, and pre-built routes
5
+ Home-page: https://github.com/AINative-Studio/core
6
+ Author: AINative Studio
7
+ Author-email: AINative Studio <dev@ainative.studio>
8
+ License: MIT
9
+ Project-URL: Homepage, https://ainative.studio/products/zerodb
10
+ Project-URL: Documentation, https://docs.ainative.studio
11
+ Project-URL: Repository, https://github.com/AINative-Studio/core
12
+ Project-URL: Bug Tracker, https://github.com/AINative-Studio/core/issues
13
+ Keywords: zerodb,fastapi,ainative,vector-database,agent-cloud,middleware,python
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: fastapi>=0.100
25
+ Requires-Dist: httpx>=0.24
26
+ Requires-Dist: pydantic>=2.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8.0; extra == "dev"
29
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
30
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
31
+ Dynamic: author
32
+ Dynamic: home-page
33
+ Dynamic: requires-python
34
+
35
+ # zerodb-fastapi
36
+
37
+ FastAPI integration for ZeroDB — router, middleware, and dependency injection helpers.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install zerodb-fastapi
43
+ ```
44
+
45
+ ## Quick Start
46
+
47
+ ```python
48
+ from fastapi import FastAPI, Depends
49
+ from zerodb_fastapi import ZeroDBMiddleware, ZeroDBRouter, ZeroDBClient, get_zerodb
50
+
51
+ app = FastAPI()
52
+
53
+ # Add middleware to inject ZeroDB client into every request
54
+ app.add_middleware(
55
+ ZeroDBMiddleware,
56
+ api_key="your-api-key",
57
+ project_id="your-project-id",
58
+ )
59
+
60
+ # Option 1: Use the pre-built router
61
+ zerodb_router = ZeroDBRouter(prefix="/zerodb")
62
+ app.include_router(zerodb_router.router)
63
+ # Provides: GET /zerodb/health, POST /zerodb/remember, POST /zerodb/recall, POST /zerodb/search
64
+
65
+ # Option 2: Use dependency injection in your own routes
66
+ @app.get("/my-search")
67
+ async def my_search(zerodb: ZeroDBClient = Depends(get_zerodb)):
68
+ results = await zerodb.recall("search query", top_k=5)
69
+ return results
70
+ ```
71
+
72
+ ## Components
73
+
74
+ ### ZeroDBMiddleware
75
+
76
+ Starlette middleware that creates a shared `ZeroDBClient` and injects it into `request.state.zerodb`.
77
+
78
+ ### ZeroDBRouter
79
+
80
+ Pre-configured APIRouter with these endpoints:
81
+ - `GET /health` — ZeroDB API health check
82
+ - `POST /remember` — Store a memory
83
+ - `POST /recall` — Recall memories by query
84
+ - `POST /search` — Semantic search
85
+
86
+ ### Dependencies
87
+
88
+ - `get_zerodb(request)` — Retrieve the ZeroDB client from request state
89
+ - `get_memory(request)` — Alias for `get_zerodb()` for memory-focused usage
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,10 @@
1
+ tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ tests/test_zerodb_fastapi.py,sha256=hSmuRay0zUv2bgCmx78vjaovim2HylNBKxIG0JENrrQ,3841
3
+ zerodb_fastapi/__init__.py,sha256=BYfu0FALmOFxI-CTBDEaGCzJTwFk8dgc0Nl1caPyslU,402
4
+ zerodb_fastapi/dependencies.py,sha256=0K5n6RKpBhCZafwWBueJ_XkWoD1y5w3jjHyl7G4QjpE,3711
5
+ zerodb_fastapi/middleware.py,sha256=BLKCWWlZyQjti6-ValE9J76-7-xOheCGss6foRV1bMw,1158
6
+ zerodb_fastapi/router.py,sha256=zdSKmkFYxfZ5nURrqaXk-Ue1kEed2uZUtkC6R9MqLrw,3329
7
+ zerodb_fastapi-0.1.0.dist-info/METADATA,sha256=ToUn8mhBbcxp5Cj1kehhjxjSVi-jI1k-rsjLDw9f17o,2882
8
+ zerodb_fastapi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ zerodb_fastapi-0.1.0.dist-info/top_level.txt,sha256=WsUztOr7BAmLUqQxx022vGWh3ZOSJKLjOKlPr-pKrEw,21
10
+ zerodb_fastapi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ tests
2
+ zerodb_fastapi