api-operator 1.0.0__tar.gz → 1.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.
- {api_operator-1.0.0 → api_operator-1.1.0}/.env.example +3 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/CHANGELOG.md +9 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/PKG-INFO +13 -6
- {api_operator-1.0.0 → api_operator-1.1.0}/README.md +5 -4
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/__init__.py +1 -1
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/agent.py +7 -1
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/config.py +5 -2
- api_operator-1.1.0/api_operator/rag/__init__.py +17 -0
- api_operator-1.1.0/api_operator/rag/embeddings.py +74 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/rag/knowledge.py +33 -2
- api_operator-1.1.0/api_operator/rag/pgvector.py +119 -0
- api_operator-1.1.0/api_operator/rag/vector.py +66 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/server/app.py +2 -2
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/ROADMAP-vNEXT.md +4 -4
- api_operator-1.1.0/docs/knowledge.md +88 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/pyproject.toml +9 -3
- api_operator-1.1.0/tests/test_embeddings.py +90 -0
- api_operator-1.0.0/api_operator/rag/__init__.py +0 -6
- api_operator-1.0.0/docs/knowledge.md +0 -46
- {api_operator-1.0.0 → api_operator-1.1.0}/.github/workflows/tests.yml +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/.gitignore +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/Dockerfile +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/LICENSE +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/__init__.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/base.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/mock.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/openapi_generator.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/registry.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/yaml_adapter.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/adapters/yaml_spec.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/audit.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/executor.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/formatters.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/guardrails.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/memory.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/planner.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/planner_openai.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/policy.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/quota.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/redaction.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/core/schemas.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/factory.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/rag/indexer.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/server/cli.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/tools/base.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/api_operator/tools/schema.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/audit.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/dry-run.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/policy.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/public-api-inventory.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/docs/quotas.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/README.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/adapter.yaml +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/policy.yaml +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/README.md +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/adapter.yaml +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/policy.yaml +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/scripts/integration_tenant_kit.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/__init__.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_agent.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_api.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_audit.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_cli.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_core.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_dry_run.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_formatters.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_integration_tenant_kit.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_knowledge.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_mock_adapter.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_openapi_policy.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_policy.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_quota.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_scenarios_e2e.py +0 -0
- {api_operator-1.0.0 → api_operator-1.1.0}/tests/test_yaml_adapter.py +0 -0
|
@@ -13,4 +13,7 @@ api_operator_DRY_RUN=false
|
|
|
13
13
|
api_operator_KNOWLEDGE_ENABLED=false
|
|
14
14
|
# api_operator_KNOWLEDGE_PATHS=docs/guide.md,README.md
|
|
15
15
|
# api_operator_KNOWLEDGE_LIMIT=3
|
|
16
|
+
# api_operator_KNOWLEDGE_BACKEND=keyword
|
|
17
|
+
# api_operator_KNOWLEDGE_EMBEDDING_MODEL=text-embedding-3-small
|
|
18
|
+
# api_operator_KNOWLEDGE_PG_DSN=postgresql+psycopg://user:pass@localhost/app
|
|
16
19
|
# api_operator_CORS_ORIGINS=http://localhost:3000
|
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.1.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **L1 embedding knowledge** (`knowledge_backend=embedding`) with OpenAI or offline hashing embedder
|
|
10
|
+
- **L2 pgvector retrieval** (`knowledge_backend=pgvector` + `knowledge_pg_dsn`)
|
|
11
|
+
- Optional extra: `pip install "api-operator[rag]"`
|
|
12
|
+
- Docs: expanded `docs/knowledge.md`
|
|
13
|
+
|
|
5
14
|
## [1.0.0] - 2026-11-23
|
|
6
15
|
|
|
7
16
|
**Safe API Agent** production label. Builds on 0.11 foundation; additive and backward compatible for existing adapters.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: api-operator
|
|
3
|
-
Version: 1.
|
|
4
|
-
Summary: Safe API Agent —
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Safe API Agent — policy, quotas, audit, and optional keyword/embedding/pgvector knowledge
|
|
5
5
|
Project-URL: Homepage, https://github.com/mohammedelkarsh/api-operator
|
|
6
6
|
Project-URL: Repository, https://github.com/mohammedelkarsh/api-operator
|
|
7
7
|
Project-URL: Issues, https://github.com/mohammedelkarsh/api-operator/issues
|
|
@@ -33,6 +33,12 @@ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
|
33
33
|
Requires-Dist: pytest>=8.2.0; extra == 'dev'
|
|
34
34
|
Provides-Extra: llm
|
|
35
35
|
Requires-Dist: openai>=1.35.0; extra == 'llm'
|
|
36
|
+
Provides-Extra: rag
|
|
37
|
+
Requires-Dist: numpy>=1.26.0; extra == 'rag'
|
|
38
|
+
Requires-Dist: openai>=1.35.0; extra == 'rag'
|
|
39
|
+
Requires-Dist: pgvector>=0.3.0; extra == 'rag'
|
|
40
|
+
Requires-Dist: psycopg[binary]>=3.1.0; extra == 'rag'
|
|
41
|
+
Requires-Dist: sqlalchemy>=2.0.0; extra == 'rag'
|
|
36
42
|
Description-Content-Type: text/markdown
|
|
37
43
|
|
|
38
44
|
# API Operator — Safe API Agent
|
|
@@ -51,9 +57,10 @@ Works with Laravel, Go, or any REST API. First-class example: [laravel-tenant-ki
|
|
|
51
57
|
## Install
|
|
52
58
|
|
|
53
59
|
```bash
|
|
54
|
-
pip install api-operator==1.
|
|
55
|
-
# optional OpenAI planner
|
|
56
|
-
pip install "api-operator[llm]==1.
|
|
60
|
+
pip install api-operator==1.1.0
|
|
61
|
+
# optional OpenAI planner / RAG (embeddings + pgvector)
|
|
62
|
+
pip install "api-operator[llm]==1.1.0"
|
|
63
|
+
pip install "api-operator[rag]==1.1.0"
|
|
57
64
|
```
|
|
58
65
|
|
|
59
66
|
Development:
|
|
@@ -89,7 +96,7 @@ api-operator chat \
|
|
|
89
96
|
| Dry-run (`--dry-run` / `dry_run=true`) | OpenAPI specs |
|
|
90
97
|
| AuditSink + redaction | API tokens in `.env` |
|
|
91
98
|
| QuotaGateway hooks | Host billing (e.g. tenant-kit meters) |
|
|
92
|
-
| Optional
|
|
99
|
+
| Optional knowledge L0/L1/L2 | Docs, embeddings, or pgvector |
|
|
93
100
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
94
101
|
|
|
95
102
|
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
@@ -14,9 +14,10 @@ Works with Laravel, Go, or any REST API. First-class example: [laravel-tenant-ki
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
16
16
|
```bash
|
|
17
|
-
pip install api-operator==1.
|
|
18
|
-
# optional OpenAI planner
|
|
19
|
-
pip install "api-operator[llm]==1.
|
|
17
|
+
pip install api-operator==1.1.0
|
|
18
|
+
# optional OpenAI planner / RAG (embeddings + pgvector)
|
|
19
|
+
pip install "api-operator[llm]==1.1.0"
|
|
20
|
+
pip install "api-operator[rag]==1.1.0"
|
|
20
21
|
```
|
|
21
22
|
|
|
22
23
|
Development:
|
|
@@ -52,7 +53,7 @@ api-operator chat \
|
|
|
52
53
|
| Dry-run (`--dry-run` / `dry_run=true`) | OpenAPI specs |
|
|
53
54
|
| AuditSink + redaction | API tokens in `.env` |
|
|
54
55
|
| QuotaGateway hooks | Host billing (e.g. tenant-kit meters) |
|
|
55
|
-
| Optional
|
|
56
|
+
| Optional knowledge L0/L1/L2 | Docs, embeddings, or pgvector |
|
|
56
57
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
57
58
|
|
|
58
59
|
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
@@ -104,6 +104,10 @@ class Agent:
|
|
|
104
104
|
enabled=self.settings.knowledge_enabled,
|
|
105
105
|
paths=self.settings.knowledge_paths,
|
|
106
106
|
adapter_docs=self.adapter.docs_paths(),
|
|
107
|
+
backend=self.settings.knowledge_backend,
|
|
108
|
+
openai_api_key=self.settings.openai_api_key,
|
|
109
|
+
embedding_model=self.settings.knowledge_embedding_model,
|
|
110
|
+
pg_dsn=self.settings.knowledge_pg_dsn,
|
|
107
111
|
)
|
|
108
112
|
|
|
109
113
|
async def chat(
|
|
@@ -226,12 +230,14 @@ class Agent:
|
|
|
226
230
|
tenant_id=tenant_id,
|
|
227
231
|
limit=self.settings.knowledge_limit,
|
|
228
232
|
)
|
|
233
|
+
backend = self.settings.knowledge_backend
|
|
229
234
|
if not hits:
|
|
230
|
-
return base, {"knowledge": {"enabled": True, "hits": 0}}
|
|
235
|
+
return base, {"knowledge": {"enabled": True, "backend": backend, "hits": 0}}
|
|
231
236
|
block = format_knowledge_context(hits)
|
|
232
237
|
meta = {
|
|
233
238
|
"knowledge": {
|
|
234
239
|
"enabled": True,
|
|
240
|
+
"backend": backend,
|
|
235
241
|
"hits": len(hits),
|
|
236
242
|
"sources": [h.source for h in hits],
|
|
237
243
|
}
|
|
@@ -22,6 +22,9 @@ class Settings(BaseSettings):
|
|
|
22
22
|
audit_path: str | None = None # JSONL file; None = NullAuditSink unless injected
|
|
23
23
|
dry_run: bool = False
|
|
24
24
|
quota_budget: float | None = None # enables InMemoryQuotaGateway when set
|
|
25
|
-
knowledge_enabled: bool = False # opt-in
|
|
26
|
-
knowledge_paths: str | None = None # comma-separated doc paths
|
|
25
|
+
knowledge_enabled: bool = False # opt-in knowledge (off by default)
|
|
26
|
+
knowledge_paths: str | None = None # comma-separated doc paths (L0/L1)
|
|
27
27
|
knowledge_limit: int = 3
|
|
28
|
+
knowledge_backend: str = "keyword" # keyword | embedding | pgvector
|
|
29
|
+
knowledge_embedding_model: str = "text-embedding-3-small"
|
|
30
|
+
knowledge_pg_dsn: str | None = None # postgres DSN for L2 pgvector
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Optional knowledge / RAG helpers (keyword L0 in core; vector extras via [rag])."""
|
|
2
|
+
|
|
3
|
+
from api_operator.rag.embeddings import Embedder, HashingEmbedder, OpenAIEmbedder
|
|
4
|
+
from api_operator.rag.indexer import DocsIndex
|
|
5
|
+
from api_operator.rag.knowledge import KeywordKnowledge, KnowledgeHit, KnowledgeStore
|
|
6
|
+
from api_operator.rag.vector import EmbeddingKnowledge
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"DocsIndex",
|
|
10
|
+
"Embedder",
|
|
11
|
+
"EmbeddingKnowledge",
|
|
12
|
+
"HashingEmbedder",
|
|
13
|
+
"KeywordKnowledge",
|
|
14
|
+
"KnowledgeHit",
|
|
15
|
+
"KnowledgeStore",
|
|
16
|
+
"OpenAIEmbedder",
|
|
17
|
+
]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Embedding backends for L1 knowledge retrieval."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from typing import Protocol, runtime_checkable
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@runtime_checkable
|
|
12
|
+
class Embedder(Protocol):
|
|
13
|
+
def embed(self, texts: list[str]) -> list[list[float]]: ...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class HashingEmbedder:
|
|
17
|
+
"""Deterministic bag-of-hashes embedder for offline tests / demos (no API)."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, dimensions: int = 64) -> None:
|
|
20
|
+
self.dimensions = dimensions
|
|
21
|
+
|
|
22
|
+
def embed(self, texts: list[str]) -> list[list[float]]:
|
|
23
|
+
return [self._one(text) for text in texts]
|
|
24
|
+
|
|
25
|
+
def _one(self, text: str) -> list[float]:
|
|
26
|
+
vec = [0.0] * self.dimensions
|
|
27
|
+
tokens = re.findall(r"[a-z0-9_]+", text.lower())
|
|
28
|
+
if not tokens:
|
|
29
|
+
return vec
|
|
30
|
+
for token in tokens:
|
|
31
|
+
digest = hashlib.sha256(token.encode("utf-8")).digest()
|
|
32
|
+
idx = int.from_bytes(digest[:4], "big") % self.dimensions
|
|
33
|
+
sign = 1.0 if digest[4] % 2 == 0 else -1.0
|
|
34
|
+
vec[idx] += sign
|
|
35
|
+
return _l2_normalize(vec)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class OpenAIEmbedder:
|
|
39
|
+
"""OpenAI embeddings API (requires ``pip install api-operator[rag]`` or ``[llm]``)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, api_key: str, model: str = "text-embedding-3-small") -> None:
|
|
42
|
+
self.api_key = api_key
|
|
43
|
+
self.model = model
|
|
44
|
+
|
|
45
|
+
def embed(self, texts: list[str]) -> list[list[float]]:
|
|
46
|
+
try:
|
|
47
|
+
from openai import OpenAI
|
|
48
|
+
except ImportError as exc:
|
|
49
|
+
raise RuntimeError(
|
|
50
|
+
"OpenAI embeddings require optional deps. Install: pip install 'api-operator[rag]'"
|
|
51
|
+
) from exc
|
|
52
|
+
client = OpenAI(api_key=self.api_key)
|
|
53
|
+
response = client.embeddings.create(model=self.model, input=texts)
|
|
54
|
+
# API may return out of order — sort by index
|
|
55
|
+
ordered = sorted(response.data, key=lambda item: item.index)
|
|
56
|
+
return [list(item.embedding) for item in ordered]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def cosine_similarity(a: list[float], b: list[float]) -> float:
|
|
60
|
+
if not a or not b or len(a) != len(b):
|
|
61
|
+
return 0.0
|
|
62
|
+
dot = sum(x * y for x, y in zip(a, b, strict=True))
|
|
63
|
+
na = math.sqrt(sum(x * x for x in a))
|
|
64
|
+
nb = math.sqrt(sum(y * y for y in b))
|
|
65
|
+
if na == 0.0 or nb == 0.0:
|
|
66
|
+
return 0.0
|
|
67
|
+
return dot / (na * nb)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _l2_normalize(vec: list[float]) -> list[float]:
|
|
71
|
+
norm = math.sqrt(sum(x * x for x in vec))
|
|
72
|
+
if norm == 0.0:
|
|
73
|
+
return vec
|
|
74
|
+
return [x / norm for x in vec]
|
|
@@ -13,7 +13,7 @@ from api_operator.rag.indexer import DocsIndex
|
|
|
13
13
|
class KnowledgeHit:
|
|
14
14
|
source: str
|
|
15
15
|
excerpt: str
|
|
16
|
-
score:
|
|
16
|
+
score: float = 0.0
|
|
17
17
|
tenant_id: str | None = None
|
|
18
18
|
|
|
19
19
|
|
|
@@ -75,7 +75,7 @@ class KeywordKnowledge:
|
|
|
75
75
|
KnowledgeHit(
|
|
76
76
|
source=source,
|
|
77
77
|
excerpt=str(item.get("excerpt") or ""),
|
|
78
|
-
score=
|
|
78
|
+
score=float(item.get("score") or 0),
|
|
79
79
|
tenant_id=_tenant_from_source(source),
|
|
80
80
|
)
|
|
81
81
|
)
|
|
@@ -116,9 +116,28 @@ def build_knowledge(
|
|
|
116
116
|
enabled: bool,
|
|
117
117
|
paths: str | None,
|
|
118
118
|
adapter_docs: list[str] | None = None,
|
|
119
|
+
backend: str = "keyword",
|
|
120
|
+
openai_api_key: str | None = None,
|
|
121
|
+
embedding_model: str = "text-embedding-3-small",
|
|
122
|
+
pg_dsn: str | None = None,
|
|
119
123
|
) -> KnowledgeStore | None:
|
|
120
124
|
if not enabled:
|
|
121
125
|
return None
|
|
126
|
+
|
|
127
|
+
mode = (backend or "keyword").strip().lower()
|
|
128
|
+
if mode == "pgvector":
|
|
129
|
+
if not pg_dsn:
|
|
130
|
+
raise ValueError("knowledge_backend=pgvector requires knowledge_pg_dsn / API_OPERATOR_KNOWLEDGE_PG_DSN")
|
|
131
|
+
from api_operator.rag.embeddings import HashingEmbedder, OpenAIEmbedder
|
|
132
|
+
from api_operator.rag.pgvector import PgVectorKnowledge
|
|
133
|
+
|
|
134
|
+
embedder = (
|
|
135
|
+
OpenAIEmbedder(openai_api_key, model=embedding_model)
|
|
136
|
+
if openai_api_key
|
|
137
|
+
else HashingEmbedder()
|
|
138
|
+
)
|
|
139
|
+
return PgVectorKnowledge(pg_dsn, embedder=embedder)
|
|
140
|
+
|
|
122
141
|
combined: list[str | Path] = []
|
|
123
142
|
if paths:
|
|
124
143
|
combined.extend(p.strip() for p in paths.split(",") if p.strip())
|
|
@@ -126,4 +145,16 @@ def build_knowledge(
|
|
|
126
145
|
combined.extend(adapter_docs)
|
|
127
146
|
if not combined:
|
|
128
147
|
return None
|
|
148
|
+
|
|
149
|
+
if mode in {"embedding", "embeddings", "vector"}:
|
|
150
|
+
from api_operator.rag.embeddings import HashingEmbedder, OpenAIEmbedder
|
|
151
|
+
from api_operator.rag.vector import EmbeddingKnowledge
|
|
152
|
+
|
|
153
|
+
embedder = (
|
|
154
|
+
OpenAIEmbedder(openai_api_key, model=embedding_model)
|
|
155
|
+
if openai_api_key
|
|
156
|
+
else HashingEmbedder()
|
|
157
|
+
)
|
|
158
|
+
return EmbeddingKnowledge(combined, embedder=embedder)
|
|
159
|
+
|
|
129
160
|
return KeywordKnowledge(combined)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""L2 Postgres + pgvector knowledge store (optional ``api-operator[rag]``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from api_operator.rag.embeddings import Embedder, HashingEmbedder
|
|
8
|
+
from api_operator.rag.knowledge import KnowledgeHit, _allowed_for_tenant, _tenant_from_source
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PgVectorKnowledge:
|
|
12
|
+
"""Query a pre-built ``api_operator_knowledge`` table with a vector column.
|
|
13
|
+
|
|
14
|
+
Expected schema (create outside the agent, e.g. Laravel migration)::
|
|
15
|
+
|
|
16
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
17
|
+
CREATE TABLE api_operator_knowledge (
|
|
18
|
+
id bigserial PRIMARY KEY,
|
|
19
|
+
source text NOT NULL,
|
|
20
|
+
excerpt text NOT NULL,
|
|
21
|
+
tenant_id text NULL,
|
|
22
|
+
embedding vector(1536) NOT NULL
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
This class only **retrieves**; indexing/upsert is left to the host app.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
dsn: str,
|
|
31
|
+
*,
|
|
32
|
+
embedder: Embedder | None = None,
|
|
33
|
+
table: str = "api_operator_knowledge",
|
|
34
|
+
embedding_column: str = "embedding",
|
|
35
|
+
) -> None:
|
|
36
|
+
self.dsn = dsn
|
|
37
|
+
self.embedder = embedder or HashingEmbedder()
|
|
38
|
+
self.table = table
|
|
39
|
+
self.embedding_column = embedding_column
|
|
40
|
+
self._engine = None
|
|
41
|
+
|
|
42
|
+
def _connect(self) -> Any:
|
|
43
|
+
if self._engine is not None:
|
|
44
|
+
return self._engine
|
|
45
|
+
try:
|
|
46
|
+
from sqlalchemy import create_engine
|
|
47
|
+
except ImportError as exc:
|
|
48
|
+
raise RuntimeError(
|
|
49
|
+
"PgVector knowledge requires sqlalchemy. Install: pip install 'api-operator[rag]'"
|
|
50
|
+
) from exc
|
|
51
|
+
self._engine = create_engine(self.dsn)
|
|
52
|
+
return self._engine
|
|
53
|
+
|
|
54
|
+
def retrieve(
|
|
55
|
+
self,
|
|
56
|
+
query: str,
|
|
57
|
+
*,
|
|
58
|
+
tenant_id: str | None = None,
|
|
59
|
+
limit: int = 3,
|
|
60
|
+
) -> list[KnowledgeHit]:
|
|
61
|
+
if not query.strip():
|
|
62
|
+
return []
|
|
63
|
+
vector = self.embedder.embed([query])[0]
|
|
64
|
+
# pgvector literal: '[1,2,3]'
|
|
65
|
+
literal = "[" + ",".join(f"{v:.8f}" for v in vector) + "]"
|
|
66
|
+
engine = self._connect()
|
|
67
|
+
try:
|
|
68
|
+
from sqlalchemy import text
|
|
69
|
+
except ImportError as exc:
|
|
70
|
+
raise RuntimeError(
|
|
71
|
+
"PgVector knowledge requires sqlalchemy. Install: pip install 'api-operator[rag]'"
|
|
72
|
+
) from exc
|
|
73
|
+
|
|
74
|
+
# Filter tenant in SQL when possible; still re-check paths for shared docs
|
|
75
|
+
sql = text(
|
|
76
|
+
f"""
|
|
77
|
+
SELECT source, excerpt, tenant_id,
|
|
78
|
+
1 - ({self.embedding_column} <=> CAST(:embedding AS vector)) AS score
|
|
79
|
+
FROM {self.table}
|
|
80
|
+
WHERE (
|
|
81
|
+
:tenant_id IS NULL AND tenant_id IS NULL
|
|
82
|
+
) OR (
|
|
83
|
+
:tenant_id IS NOT NULL AND (tenant_id IS NULL OR tenant_id = :tenant_id)
|
|
84
|
+
)
|
|
85
|
+
ORDER BY {self.embedding_column} <=> CAST(:embedding AS vector)
|
|
86
|
+
LIMIT :limit
|
|
87
|
+
"""
|
|
88
|
+
)
|
|
89
|
+
with engine.connect() as conn:
|
|
90
|
+
rows = conn.execute(
|
|
91
|
+
sql,
|
|
92
|
+
{"embedding": literal, "tenant_id": tenant_id, "limit": max(limit * 2, 6)},
|
|
93
|
+
).mappings().all()
|
|
94
|
+
|
|
95
|
+
hits: list[KnowledgeHit] = []
|
|
96
|
+
for row in rows:
|
|
97
|
+
source = str(row["source"])
|
|
98
|
+
# Path-based isolation still applies for filesystem-style sources
|
|
99
|
+
if source and not _allowed_for_tenant(source, tenant_id):
|
|
100
|
+
owned = row.get("tenant_id")
|
|
101
|
+
if owned is not None and tenant_id is not None and str(owned) != tenant_id:
|
|
102
|
+
continue
|
|
103
|
+
if owned is not None and tenant_id is None:
|
|
104
|
+
continue
|
|
105
|
+
hits.append(
|
|
106
|
+
KnowledgeHit(
|
|
107
|
+
source=source,
|
|
108
|
+
excerpt=str(row["excerpt"]),
|
|
109
|
+
score=float(row["score"] or 0),
|
|
110
|
+
tenant_id=(
|
|
111
|
+
str(row["tenant_id"])
|
|
112
|
+
if row.get("tenant_id") is not None
|
|
113
|
+
else _tenant_from_source(source)
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
if len(hits) >= limit:
|
|
118
|
+
break
|
|
119
|
+
return hits
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""L1 in-memory / local vector knowledge store."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from api_operator.rag.embeddings import Embedder, HashingEmbedder, cosine_similarity
|
|
9
|
+
from api_operator.rag.indexer import DocsIndex
|
|
10
|
+
from api_operator.rag.knowledge import KnowledgeHit, _allowed_for_tenant, _tenant_from_source
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(slots=True)
|
|
14
|
+
class _VectorChunk:
|
|
15
|
+
source: str
|
|
16
|
+
excerpt: str
|
|
17
|
+
vector: list[float]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EmbeddingKnowledge:
|
|
21
|
+
"""L1 semantic search over doc chunks with an inject Embedder."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
paths: list[str | Path],
|
|
26
|
+
*,
|
|
27
|
+
embedder: Embedder | None = None,
|
|
28
|
+
) -> None:
|
|
29
|
+
self.embedder = embedder or HashingEmbedder()
|
|
30
|
+
index = DocsIndex(list(paths))
|
|
31
|
+
texts = [chunk for _, chunk in index.chunks]
|
|
32
|
+
vectors = self.embedder.embed(texts) if texts else []
|
|
33
|
+
self._chunks: list[_VectorChunk] = [
|
|
34
|
+
_VectorChunk(source=source, excerpt=chunk[:500], vector=vector)
|
|
35
|
+
for (source, chunk), vector in zip(index.chunks, vectors, strict=True)
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
def retrieve(
|
|
39
|
+
self,
|
|
40
|
+
query: str,
|
|
41
|
+
*,
|
|
42
|
+
tenant_id: str | None = None,
|
|
43
|
+
limit: int = 3,
|
|
44
|
+
) -> list[KnowledgeHit]:
|
|
45
|
+
if not self._chunks or not query.strip():
|
|
46
|
+
return []
|
|
47
|
+
query_vec = self.embedder.embed([query])[0]
|
|
48
|
+
scored: list[tuple[float, _VectorChunk]] = []
|
|
49
|
+
for chunk in self._chunks:
|
|
50
|
+
if not _allowed_for_tenant(chunk.source, tenant_id):
|
|
51
|
+
continue
|
|
52
|
+
score = cosine_similarity(query_vec, chunk.vector)
|
|
53
|
+
if score > 0:
|
|
54
|
+
scored.append((score, chunk))
|
|
55
|
+
scored.sort(key=lambda item: item[0], reverse=True)
|
|
56
|
+
hits: list[KnowledgeHit] = []
|
|
57
|
+
for score, chunk in scored[:limit]:
|
|
58
|
+
hits.append(
|
|
59
|
+
KnowledgeHit(
|
|
60
|
+
source=chunk.source,
|
|
61
|
+
excerpt=chunk.excerpt,
|
|
62
|
+
score=score,
|
|
63
|
+
tenant_id=_tenant_from_source(chunk.source),
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
return hits
|
|
@@ -44,8 +44,8 @@ def create_app(settings: Settings | None = None):
|
|
|
44
44
|
session_store = SessionStore()
|
|
45
45
|
app = FastAPI(
|
|
46
46
|
title="API Operator",
|
|
47
|
-
version="1.
|
|
48
|
-
description="Safe API Agent — policy, dry-run, audit, optional knowledge",
|
|
47
|
+
version="1.1.0",
|
|
48
|
+
description="Safe API Agent — policy, dry-run, audit, optional knowledge/RAG",
|
|
49
49
|
)
|
|
50
50
|
|
|
51
51
|
origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
|
|
@@ -268,14 +268,14 @@ User message
|
|
|
268
268
|
- `docs/audit.md`
|
|
269
269
|
- `docs/quotas.md`
|
|
270
270
|
- `docs/dry-run.md`
|
|
271
|
-
4. [x] نشر PyPI `api-operator==0.
|
|
272
|
-
5. [x] Tag Git `
|
|
271
|
+
4. [x] نشر PyPI `api-operator==1.0.0` (بعد Foundation `0.11.0`).
|
|
272
|
+
5. [x] Tag Git `v1.0.0`.
|
|
273
273
|
|
|
274
274
|
**Done للمرحلة 1 كاملة:**
|
|
275
275
|
- [x] Policy + Dry-run + Audit + Quota hooks تعمل معًا في مسار chat واحد.
|
|
276
276
|
- [x] الاختبارات الخضراء على CI.
|
|
277
277
|
- [x] لا يوجد اعتماد إجباري على Laravel أو vector DB.
|
|
278
|
-
- [x] الحزمة منشورة: `pip install api-operator==0.
|
|
278
|
+
- [x] الحزمة منشورة: `pip install api-operator==1.0.0` — https://pypi.org/project/api-operator/1.0.0/
|
|
279
279
|
|
|
280
280
|
---
|
|
281
281
|
|
|
@@ -362,7 +362,7 @@ rag = ["pgvector...", "sqlalchemy..."] # يُحدد بدقة عند التنف
|
|
|
362
362
|
- [x] عزل tenant على مستوى الفهرس/الاستعلام.
|
|
363
363
|
- [x] مقاييس بسيطة: metadata.knowledge.hits / sources على الرد (تحسين اختيار الأداة يُقاس لاحقًا مع L1).
|
|
364
364
|
- [x] وثيقة `docs/knowledge.md`.
|
|
365
|
-
- [
|
|
365
|
+
- [x] L1 embeddings + L2 pgvector retrieval (`api-operator[rag]`, إصدار 1.1.0).
|
|
366
366
|
|
|
367
367
|
---
|
|
368
368
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Knowledge (RAG) — opt-in
|
|
2
|
+
|
|
3
|
+
Knowledge helps the planner choose the right tool. It is **off by default**.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
export API_OPERATOR_KNOWLEDGE_ENABLED=true
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Backends
|
|
10
|
+
|
|
11
|
+
| Backend | Setting | Needs | Notes |
|
|
12
|
+
|---------|---------|--------|--------|
|
|
13
|
+
| **keyword** (L0) | `API_OPERATOR_KNOWLEDGE_BACKEND=keyword` | core only | Default when knowledge is enabled |
|
|
14
|
+
| **embedding** (L1) | `…=embedding` | optional OpenAI key; else hashing embedder | In-memory vectors at startup |
|
|
15
|
+
| **pgvector** (L2) | `…=pgvector` | `pip install 'api-operator[rag]'` + DSN | Host owns indexing |
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
export API_OPERATOR_KNOWLEDGE_PATHS="docs/api.md,README.md"
|
|
19
|
+
export API_OPERATOR_KNOWLEDGE_BACKEND=keyword # or embedding
|
|
20
|
+
# export API_OPERATOR_OPENAI_API_KEY=... # for OpenAI embeddings
|
|
21
|
+
# export API_OPERATOR_KNOWLEDGE_PG_DSN=postgresql+psycopg://...
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## L0 — Keyword
|
|
25
|
+
|
|
26
|
+
No embeddings. Best for small curated docs.
|
|
27
|
+
|
|
28
|
+
## L1 — Embedding (local index)
|
|
29
|
+
|
|
30
|
+
Chunks docs at agent start, embeds them, ranks by cosine similarity.
|
|
31
|
+
|
|
32
|
+
- With `API_OPERATOR_OPENAI_API_KEY`: uses `text-embedding-3-small` (override via `API_OPERATOR_KNOWLEDGE_EMBEDDING_MODEL`)
|
|
33
|
+
- Without a key: uses a deterministic **hashing embedder** (fine for demos/tests, weaker quality)
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from api_operator.rag import EmbeddingKnowledge, HashingEmbedder
|
|
37
|
+
from api_operator.factory import build_agent
|
|
38
|
+
from api_operator.core.config import Settings
|
|
39
|
+
|
|
40
|
+
knowledge = EmbeddingKnowledge(["docs/guide.md"], embedder=HashingEmbedder())
|
|
41
|
+
agent = build_agent(
|
|
42
|
+
"mock",
|
|
43
|
+
knowledge=knowledge,
|
|
44
|
+
settings=Settings(knowledge_enabled=True, knowledge_backend="embedding"),
|
|
45
|
+
)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## L2 — Postgres + pgvector
|
|
49
|
+
|
|
50
|
+
Retrieval-only against a table you maintain (e.g. from Laravel):
|
|
51
|
+
|
|
52
|
+
```sql
|
|
53
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
54
|
+
CREATE TABLE api_operator_knowledge (
|
|
55
|
+
id bigserial PRIMARY KEY,
|
|
56
|
+
source text NOT NULL,
|
|
57
|
+
excerpt text NOT NULL,
|
|
58
|
+
tenant_id text NULL,
|
|
59
|
+
embedding vector(1536) NOT NULL
|
|
60
|
+
);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install "api-operator[rag]"
|
|
65
|
+
export API_OPERATOR_KNOWLEDGE_ENABLED=true
|
|
66
|
+
export API_OPERATOR_KNOWLEDGE_BACKEND=pgvector
|
|
67
|
+
export API_OPERATOR_KNOWLEDGE_PG_DSN="postgresql+psycopg://user:pass@localhost/app"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Tenant isolation
|
|
71
|
+
|
|
72
|
+
Paths containing `/tenants/{tenant_id}/` (and pgvector `tenant_id` column) stay private:
|
|
73
|
+
|
|
74
|
+
- No `tenant_id` on `/v1/chat` → shared docs only
|
|
75
|
+
- `tenant_id=acme` → shared + acme — never another tenant
|
|
76
|
+
|
|
77
|
+
## Response metadata
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
"metadata": {
|
|
81
|
+
"knowledge": {
|
|
82
|
+
"enabled": true,
|
|
83
|
+
"backend": "embedding",
|
|
84
|
+
"hits": 2,
|
|
85
|
+
"sources": ["docs/guide.md"]
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "api-operator"
|
|
7
|
-
version = "1.
|
|
8
|
-
description = "Safe API Agent —
|
|
7
|
+
version = "1.1.0"
|
|
8
|
+
description = "Safe API Agent — policy, quotas, audit, and optional keyword/embedding/pgvector knowledge"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
11
11
|
license = "MIT"
|
|
@@ -35,8 +35,14 @@ dependencies = [
|
|
|
35
35
|
|
|
36
36
|
[project.optional-dependencies]
|
|
37
37
|
llm = ["openai>=1.35.0"]
|
|
38
|
+
rag = [
|
|
39
|
+
"openai>=1.35.0",
|
|
40
|
+
"numpy>=1.26.0",
|
|
41
|
+
"sqlalchemy>=2.0.0",
|
|
42
|
+
"psycopg[binary]>=3.1.0",
|
|
43
|
+
"pgvector>=0.3.0",
|
|
44
|
+
]
|
|
38
45
|
dev = ["pytest>=8.2.0", "pytest-asyncio>=0.23.0", "httpx>=0.27.0"]
|
|
39
|
-
# `rag` extra (pgvector / embeddings) lands in 1.1.0 — keyword L0 needs no extra.
|
|
40
46
|
|
|
41
47
|
[project.scripts]
|
|
42
48
|
api-operator = "api_operator.server.cli:app"
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from api_operator.core.config import Settings
|
|
8
|
+
from api_operator.factory import build_agent
|
|
9
|
+
from api_operator.rag.embeddings import HashingEmbedder, cosine_similarity
|
|
10
|
+
from api_operator.rag.knowledge import build_knowledge
|
|
11
|
+
from api_operator.rag.vector import EmbeddingKnowledge
|
|
12
|
+
from api_operator.adapters.mock import reset_mock_store
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture(autouse=True)
|
|
16
|
+
def clean_store():
|
|
17
|
+
reset_mock_store()
|
|
18
|
+
yield
|
|
19
|
+
reset_mock_store()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_hashing_embedder_is_deterministic():
|
|
23
|
+
emb = HashingEmbedder(dimensions=32)
|
|
24
|
+
a = emb.embed(["create workspace tool"])[0]
|
|
25
|
+
b = emb.embed(["create workspace tool"])[0]
|
|
26
|
+
assert a == b
|
|
27
|
+
assert cosine_similarity(a, a) == pytest.approx(1.0)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_embedding_knowledge_ranks_related_docs(tmp_path: Path):
|
|
31
|
+
related = tmp_path / "workspaces.md"
|
|
32
|
+
related.write_text(
|
|
33
|
+
"Use the create_workspace tool when the user wants a new workspace subdomain.\n\n"
|
|
34
|
+
"Always confirm dangerous workspace creation before calling the API.",
|
|
35
|
+
encoding="utf-8",
|
|
36
|
+
)
|
|
37
|
+
unrelated = tmp_path / "cooking.md"
|
|
38
|
+
unrelated.write_text(
|
|
39
|
+
"Pasta recipes with tomato sauce and basil are unrelated to SaaS tooling.\n\n"
|
|
40
|
+
"Dessert ideas include chocolate cake and vanilla ice cream for parties.",
|
|
41
|
+
encoding="utf-8",
|
|
42
|
+
)
|
|
43
|
+
store = EmbeddingKnowledge([related, unrelated], embedder=HashingEmbedder())
|
|
44
|
+
hits = store.retrieve("create workspace subdomain", limit=2)
|
|
45
|
+
assert hits
|
|
46
|
+
assert "workspaces.md" in hits[0].source
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_build_knowledge_embedding_backend(tmp_path: Path):
|
|
50
|
+
doc = tmp_path / "guide.md"
|
|
51
|
+
doc.write_text(
|
|
52
|
+
"List workspaces with the list_workspaces tool from the operator chat flow.\n\n"
|
|
53
|
+
"Guided agent buttons help users discover workspace listing commands.",
|
|
54
|
+
encoding="utf-8",
|
|
55
|
+
)
|
|
56
|
+
store = build_knowledge(
|
|
57
|
+
enabled=True,
|
|
58
|
+
paths=str(doc),
|
|
59
|
+
backend="embedding",
|
|
60
|
+
)
|
|
61
|
+
assert store is not None
|
|
62
|
+
hits = store.retrieve("list workspaces tool")
|
|
63
|
+
assert len(hits) >= 1
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.asyncio
|
|
67
|
+
async def test_agent_embedding_backend_metadata(tmp_path: Path):
|
|
68
|
+
doc = tmp_path / "guide.md"
|
|
69
|
+
doc.write_text(
|
|
70
|
+
"To list workspaces use the list_workspaces tool from the operator chat.\n\n"
|
|
71
|
+
"This paragraph explains workspace listing for the guided agent.",
|
|
72
|
+
encoding="utf-8",
|
|
73
|
+
)
|
|
74
|
+
agent = build_agent(
|
|
75
|
+
"mock",
|
|
76
|
+
settings=Settings(
|
|
77
|
+
planner="mock",
|
|
78
|
+
knowledge_enabled=True,
|
|
79
|
+
knowledge_paths=str(doc),
|
|
80
|
+
knowledge_backend="embedding",
|
|
81
|
+
),
|
|
82
|
+
)
|
|
83
|
+
response = await agent.chat("list workspaces", abilities=["workspaces:read"])
|
|
84
|
+
assert response.metadata["knowledge"]["backend"] == "embedding"
|
|
85
|
+
assert response.metadata["knowledge"]["hits"] >= 1
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_pgvector_requires_dsn():
|
|
89
|
+
with pytest.raises(ValueError, match="knowledge_pg_dsn"):
|
|
90
|
+
build_knowledge(enabled=True, paths=None, backend="pgvector", pg_dsn=None)
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
"""Optional knowledge / RAG helpers (keyword L0 in core; vector extras later)."""
|
|
2
|
-
|
|
3
|
-
from api_operator.rag.indexer import DocsIndex
|
|
4
|
-
from api_operator.rag.knowledge import KeywordKnowledge, KnowledgeHit, KnowledgeStore
|
|
5
|
-
|
|
6
|
-
__all__ = ["DocsIndex", "KeywordKnowledge", "KnowledgeHit", "KnowledgeStore"]
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
# Knowledge (RAG) — opt-in
|
|
2
|
-
|
|
3
|
-
Knowledge helps the planner choose the right tool. It is **off by default**.
|
|
4
|
-
|
|
5
|
-
## L0 — Keyword (ships in core / 1.0+)
|
|
6
|
-
|
|
7
|
-
No embeddings, no extra packages.
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
export API_OPERATOR_KNOWLEDGE_ENABLED=true
|
|
11
|
-
export API_OPERATOR_KNOWLEDGE_PATHS="docs/api.md,README.md"
|
|
12
|
-
api-operator chat --adapter mock
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
Or inject a store:
|
|
16
|
-
|
|
17
|
-
```python
|
|
18
|
-
from api_operator.rag import KeywordKnowledge
|
|
19
|
-
from api_operator.factory import build_agent
|
|
20
|
-
|
|
21
|
-
knowledge = KeywordKnowledge(["docs/guide.md"])
|
|
22
|
-
agent = build_agent("mock", knowledge=knowledge, settings=Settings(knowledge_enabled=True))
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
Retrieved excerpts are appended to the planner `system_prompt`. Responses may include:
|
|
26
|
-
|
|
27
|
-
```json
|
|
28
|
-
"metadata": { "knowledge": { "enabled": true, "hits": 2, "sources": ["..."] } }
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
### Tenant isolation
|
|
32
|
-
|
|
33
|
-
Paths containing `/tenants/{tenant_id}/` are private to that tenant:
|
|
34
|
-
|
|
35
|
-
- Without `tenant_id` on `/v1/chat`: only shared docs (no `/tenants/` segment)
|
|
36
|
-
- With `tenant_id=acme`: shared docs + `/tenants/acme/**` only — never another tenant
|
|
37
|
-
|
|
38
|
-
## L1 / L2 — planned (1.1+)
|
|
39
|
-
|
|
40
|
-
| Layer | Tech | Extra |
|
|
41
|
-
|-------|------|--------|
|
|
42
|
-
| L1 | Local embeddings | `pip install api-operator[rag]` (future) |
|
|
43
|
-
| L2 | Postgres + pgvector | same extra |
|
|
44
|
-
| L3 | Pinecone / Qdrant | later drivers |
|
|
45
|
-
|
|
46
|
-
Keyword L0 remains available without the extra.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|