api-operator 0.11.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-0.11.0 → api_operator-1.1.0}/.env.example +6 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/CHANGELOG.md +23 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/PKG-INFO +14 -6
- {api_operator-0.11.0 → api_operator-1.1.0}/README.md +6 -4
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/__init__.py +1 -1
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/agent.py +80 -6
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/config.py +6 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/factory.py +3 -0
- 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-0.11.0 → api_operator-1.1.0}/api_operator/rag/indexer.py +2 -2
- api_operator-1.1.0/api_operator/rag/knowledge.py +160 -0
- 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-0.11.0 → api_operator-1.1.0}/api_operator/server/app.py +2 -2
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/ROADMAP-vNEXT.md +9 -8
- api_operator-1.1.0/docs/knowledge.md +88 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/pyproject.toml +9 -2
- api_operator-1.1.0/tests/test_embeddings.py +90 -0
- api_operator-1.1.0/tests/test_knowledge.py +81 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/.github/workflows/tests.yml +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/.gitignore +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/Dockerfile +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/LICENSE +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/__init__.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/base.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/mock.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/openapi_generator.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/registry.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/yaml_adapter.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/adapters/yaml_spec.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/audit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/executor.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/formatters.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/guardrails.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/memory.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/planner.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/planner_openai.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/quota.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/redaction.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/core/schemas.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/server/cli.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/tools/base.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/api_operator/tools/schema.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/audit.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/dry-run.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/policy.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/public-api-inventory.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/docs/quotas.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/README.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/adapter.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/jsonplaceholder-adapter/policy.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/README.md +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/adapter.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/examples/tenant-kit-adapter/policy.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/scripts/integration_tenant_kit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/__init__.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_agent.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_api.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_audit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_cli.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_core.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_dry_run.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_formatters.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_integration_tenant_kit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_mock_adapter.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_openapi_policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_quota.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_scenarios_e2e.py +0 -0
- {api_operator-0.11.0 → api_operator-1.1.0}/tests/test_yaml_adapter.py +0 -0
|
@@ -10,4 +10,10 @@ api_operator_AUDIT_ENABLED=true
|
|
|
10
10
|
# api_operator_POLICY_PATH=./policy.yaml
|
|
11
11
|
# api_operator_QUOTA_BUDGET=100
|
|
12
12
|
api_operator_DRY_RUN=false
|
|
13
|
+
api_operator_KNOWLEDGE_ENABLED=false
|
|
14
|
+
# api_operator_KNOWLEDGE_PATHS=docs/guide.md,README.md
|
|
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
|
|
13
19
|
# api_operator_CORS_ORIGINS=http://localhost:3000
|
|
@@ -2,6 +2,29 @@
|
|
|
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
|
+
|
|
14
|
+
## [1.0.0] - 2026-11-23
|
|
15
|
+
|
|
16
|
+
**Safe API Agent** production label. Builds on 0.11 foundation; additive and backward compatible for existing adapters.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- Opt-in **keyword knowledge (L0)**: `API_OPERATOR_KNOWLEDGE_ENABLED` + `KNOWLEDGE_PATHS`
|
|
21
|
+
- Tenant-scoped doc isolation under `/tenants/{id}/`
|
|
22
|
+
- `docs/knowledge.md` (L1+ `rag` extra deferred to 1.1.0)
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- Package version **1.0.0**; README / FastAPI metadata aligned
|
|
27
|
+
|
|
5
28
|
## [0.11.0] - 2026-11-23
|
|
6
29
|
|
|
7
30
|
Foundation for **Safe API Agent** (see `docs/ROADMAP-vNEXT.md`). Opt-in; existing adapters keep working.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: api-operator
|
|
3
|
-
Version:
|
|
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
|
|
55
|
-
# optional OpenAI planner
|
|
56
|
-
pip install "api-operator[llm]"
|
|
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,9 +96,10 @@ 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) |
|
|
99
|
+
| Optional knowledge L0/L1/L2 | Docs, embeddings, or pgvector |
|
|
92
100
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
93
101
|
|
|
94
|
-
No hard dependency on Laravel, Postgres, or vector DBs.
|
|
102
|
+
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
95
103
|
|
|
96
104
|
## Safe by default
|
|
97
105
|
|
|
@@ -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
|
|
18
|
-
# optional OpenAI planner
|
|
19
|
-
pip install "api-operator[llm]"
|
|
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,9 +53,10 @@ 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) |
|
|
56
|
+
| Optional knowledge L0/L1/L2 | Docs, embeddings, or pgvector |
|
|
55
57
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
56
58
|
|
|
57
|
-
No hard dependency on Laravel, Postgres, or vector DBs.
|
|
59
|
+
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
58
60
|
|
|
59
61
|
## Safe by default
|
|
60
62
|
|
|
@@ -33,6 +33,11 @@ from api_operator.core.schemas import (
|
|
|
33
33
|
PolicyDecision,
|
|
34
34
|
QuotaDecision,
|
|
35
35
|
)
|
|
36
|
+
from api_operator.rag.knowledge import (
|
|
37
|
+
KnowledgeStore,
|
|
38
|
+
build_knowledge,
|
|
39
|
+
format_knowledge_context,
|
|
40
|
+
)
|
|
36
41
|
from api_operator.tools.base import ToolRegistry
|
|
37
42
|
|
|
38
43
|
|
|
@@ -58,6 +63,7 @@ class Agent:
|
|
|
58
63
|
policy_path: str | Path | None = None,
|
|
59
64
|
audit: AuditSink | None = None,
|
|
60
65
|
quota: QuotaGateway | None = None,
|
|
66
|
+
knowledge: KnowledgeStore | None = None,
|
|
61
67
|
) -> None:
|
|
62
68
|
self.settings = settings or Settings()
|
|
63
69
|
self.adapter = adapter
|
|
@@ -91,6 +97,19 @@ class Agent:
|
|
|
91
97
|
else:
|
|
92
98
|
self.quota = UnlimitedQuotaGateway()
|
|
93
99
|
|
|
100
|
+
if knowledge is not None:
|
|
101
|
+
self.knowledge = knowledge
|
|
102
|
+
else:
|
|
103
|
+
self.knowledge = build_knowledge(
|
|
104
|
+
enabled=self.settings.knowledge_enabled,
|
|
105
|
+
paths=self.settings.knowledge_paths,
|
|
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,
|
|
111
|
+
)
|
|
112
|
+
|
|
94
113
|
async def chat(
|
|
95
114
|
self,
|
|
96
115
|
message: str,
|
|
@@ -135,33 +154,57 @@ class Agent:
|
|
|
135
154
|
session.add("assistant", reply, status="ok")
|
|
136
155
|
return AgentResponse(session_id=session.id, message=reply, status="ok")
|
|
137
156
|
|
|
157
|
+
system_prompt, knowledge_meta = self._system_prompt_with_knowledge(
|
|
158
|
+
message,
|
|
159
|
+
tenant_id=tenant_id,
|
|
160
|
+
)
|
|
138
161
|
plan = await self.planner.plan(
|
|
139
162
|
message=message,
|
|
140
163
|
registry=self.registry,
|
|
141
164
|
history=session.history(),
|
|
142
|
-
system_prompt=
|
|
165
|
+
system_prompt=system_prompt,
|
|
143
166
|
)
|
|
144
167
|
|
|
145
168
|
if plan.type == "respond":
|
|
146
169
|
session.add("assistant", plan.content, status="ok")
|
|
147
|
-
return AgentResponse(
|
|
170
|
+
return AgentResponse(
|
|
171
|
+
session_id=session.id,
|
|
172
|
+
message=plan.content,
|
|
173
|
+
status="ok",
|
|
174
|
+
metadata=knowledge_meta,
|
|
175
|
+
)
|
|
148
176
|
|
|
149
177
|
if plan.type == "clarify":
|
|
150
178
|
session.add("assistant", plan.content, status="ok")
|
|
151
|
-
return AgentResponse(
|
|
179
|
+
return AgentResponse(
|
|
180
|
+
session_id=session.id,
|
|
181
|
+
message=plan.content,
|
|
182
|
+
status="ok",
|
|
183
|
+
metadata=knowledge_meta,
|
|
184
|
+
)
|
|
152
185
|
|
|
153
186
|
if plan.type != "tool" or not plan.tool_name:
|
|
154
187
|
reply = "Could not determine an action."
|
|
155
188
|
session.add("assistant", reply, status="error")
|
|
156
|
-
return AgentResponse(
|
|
189
|
+
return AgentResponse(
|
|
190
|
+
session_id=session.id,
|
|
191
|
+
message=reply,
|
|
192
|
+
status="error",
|
|
193
|
+
metadata=knowledge_meta,
|
|
194
|
+
)
|
|
157
195
|
|
|
158
196
|
tool = self.registry.get(plan.tool_name)
|
|
159
197
|
if tool is None:
|
|
160
198
|
reply = f"Tool not found: {plan.tool_name}"
|
|
161
199
|
session.add("assistant", reply, status="error")
|
|
162
|
-
return AgentResponse(
|
|
200
|
+
return AgentResponse(
|
|
201
|
+
session_id=session.id,
|
|
202
|
+
message=reply,
|
|
203
|
+
status="error",
|
|
204
|
+
metadata=knowledge_meta,
|
|
205
|
+
)
|
|
163
206
|
|
|
164
|
-
|
|
207
|
+
response = await self._run_tool(
|
|
165
208
|
session,
|
|
166
209
|
plan.tool_name,
|
|
167
210
|
plan.tool_args or {},
|
|
@@ -169,6 +212,37 @@ class Agent:
|
|
|
169
212
|
skip_confirmation=auto_confirm,
|
|
170
213
|
dry_run=use_dry_run,
|
|
171
214
|
)
|
|
215
|
+
if knowledge_meta:
|
|
216
|
+
response.metadata = {**knowledge_meta, **response.metadata}
|
|
217
|
+
return response
|
|
218
|
+
|
|
219
|
+
def _system_prompt_with_knowledge(
|
|
220
|
+
self,
|
|
221
|
+
message: str,
|
|
222
|
+
*,
|
|
223
|
+
tenant_id: str | None,
|
|
224
|
+
) -> tuple[str, dict[str, Any]]:
|
|
225
|
+
base = self.adapter.system_prompt()
|
|
226
|
+
if self.knowledge is None:
|
|
227
|
+
return base, {}
|
|
228
|
+
hits = self.knowledge.retrieve(
|
|
229
|
+
message,
|
|
230
|
+
tenant_id=tenant_id,
|
|
231
|
+
limit=self.settings.knowledge_limit,
|
|
232
|
+
)
|
|
233
|
+
backend = self.settings.knowledge_backend
|
|
234
|
+
if not hits:
|
|
235
|
+
return base, {"knowledge": {"enabled": True, "backend": backend, "hits": 0}}
|
|
236
|
+
block = format_knowledge_context(hits)
|
|
237
|
+
meta = {
|
|
238
|
+
"knowledge": {
|
|
239
|
+
"enabled": True,
|
|
240
|
+
"backend": backend,
|
|
241
|
+
"hits": len(hits),
|
|
242
|
+
"sources": [h.source for h in hits],
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return f"{base}\n\n{block}", meta
|
|
172
246
|
|
|
173
247
|
async def _run_tool(
|
|
174
248
|
self,
|
|
@@ -22,3 +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 knowledge (off by default)
|
|
26
|
+
knowledge_paths: str | None = None # comma-separated doc paths (L0/L1)
|
|
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
|
|
@@ -9,6 +9,7 @@ from api_operator.core.config import Settings
|
|
|
9
9
|
from api_operator.core.memory import SessionStore
|
|
10
10
|
from api_operator.core.policy import PolicyEngine
|
|
11
11
|
from api_operator.core.quota import QuotaGateway
|
|
12
|
+
from api_operator.rag.knowledge import KnowledgeStore
|
|
12
13
|
from api_operator.adapters.registry import load_adapter
|
|
13
14
|
|
|
14
15
|
|
|
@@ -38,6 +39,7 @@ def build_agent(
|
|
|
38
39
|
policy_path: str | None = None,
|
|
39
40
|
audit: AuditSink | None = None,
|
|
40
41
|
quota: QuotaGateway | None = None,
|
|
42
|
+
knowledge: KnowledgeStore | None = None,
|
|
41
43
|
**adapter_kwargs: Any,
|
|
42
44
|
) -> Agent:
|
|
43
45
|
settings = settings or Settings()
|
|
@@ -56,4 +58,5 @@ def build_agent(
|
|
|
56
58
|
policy_path=resolved,
|
|
57
59
|
audit=audit,
|
|
58
60
|
quota=quota,
|
|
61
|
+
knowledge=knowledge,
|
|
59
62
|
)
|
|
@@ -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]
|
|
@@ -32,6 +32,6 @@ class DocsIndex:
|
|
|
32
32
|
scored.append((score, source, chunk))
|
|
33
33
|
scored.sort(key=lambda item: item[0], reverse=True)
|
|
34
34
|
return [
|
|
35
|
-
{"source": source, "excerpt": chunk[:500]}
|
|
36
|
-
for
|
|
35
|
+
{"source": source, "excerpt": chunk[:500], "score": score}
|
|
36
|
+
for score, source, chunk in scored[:limit]
|
|
37
37
|
]
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Knowledge retrieval for Safe API Agent (opt-in, off by default)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Protocol, runtime_checkable
|
|
8
|
+
|
|
9
|
+
from api_operator.rag.indexer import DocsIndex
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(slots=True)
|
|
13
|
+
class KnowledgeHit:
|
|
14
|
+
source: str
|
|
15
|
+
excerpt: str
|
|
16
|
+
score: float = 0.0
|
|
17
|
+
tenant_id: str | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@runtime_checkable
|
|
21
|
+
class KnowledgeStore(Protocol):
|
|
22
|
+
def retrieve(
|
|
23
|
+
self,
|
|
24
|
+
query: str,
|
|
25
|
+
*,
|
|
26
|
+
tenant_id: str | None = None,
|
|
27
|
+
limit: int = 3,
|
|
28
|
+
) -> list[KnowledgeHit]: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class KeywordKnowledge:
|
|
32
|
+
"""L0 keyword store with optional per-tenant path isolation.
|
|
33
|
+
|
|
34
|
+
Shared docs live at the top-level paths. Tenant-scoped docs may live under
|
|
35
|
+
a subdirectory named after ``tenant_id`` (or containing ``/tenants/{id}/``).
|
|
36
|
+
When ``tenant_id`` is set, shared docs remain visible and only that tenant's
|
|
37
|
+
private docs are included — never other tenants'.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
paths: list[str | Path] | None = None,
|
|
43
|
+
*,
|
|
44
|
+
index: DocsIndex | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
if index is not None:
|
|
47
|
+
self._index = index
|
|
48
|
+
else:
|
|
49
|
+
self._index = DocsIndex(list(paths or []))
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_settings_paths(cls, raw: str | None) -> KeywordKnowledge | None:
|
|
53
|
+
"""Parse comma-separated paths; return None if empty."""
|
|
54
|
+
if not raw or not raw.strip():
|
|
55
|
+
return None
|
|
56
|
+
paths = [p.strip() for p in raw.split(",") if p.strip()]
|
|
57
|
+
if not paths:
|
|
58
|
+
return None
|
|
59
|
+
return cls(paths)
|
|
60
|
+
|
|
61
|
+
def retrieve(
|
|
62
|
+
self,
|
|
63
|
+
query: str,
|
|
64
|
+
*,
|
|
65
|
+
tenant_id: str | None = None,
|
|
66
|
+
limit: int = 3,
|
|
67
|
+
) -> list[KnowledgeHit]:
|
|
68
|
+
raw = self._index.search(query, limit=max(limit * 4, 12))
|
|
69
|
+
hits: list[KnowledgeHit] = []
|
|
70
|
+
for item in raw:
|
|
71
|
+
source = str(item.get("source") or "")
|
|
72
|
+
if not _allowed_for_tenant(source, tenant_id):
|
|
73
|
+
continue
|
|
74
|
+
hits.append(
|
|
75
|
+
KnowledgeHit(
|
|
76
|
+
source=source,
|
|
77
|
+
excerpt=str(item.get("excerpt") or ""),
|
|
78
|
+
score=float(item.get("score") or 0),
|
|
79
|
+
tenant_id=_tenant_from_source(source),
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
if len(hits) >= limit:
|
|
83
|
+
break
|
|
84
|
+
return hits
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def format_knowledge_context(hits: list[KnowledgeHit]) -> str:
|
|
88
|
+
if not hits:
|
|
89
|
+
return ""
|
|
90
|
+
lines = ["Relevant documentation excerpts (use only if helpful for tool choice):"]
|
|
91
|
+
for idx, hit in enumerate(hits, start=1):
|
|
92
|
+
lines.append(f"[{idx}] ({hit.source})\n{hit.excerpt}")
|
|
93
|
+
return "\n\n".join(lines)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _tenant_from_source(source: str) -> str | None:
|
|
97
|
+
normalized = source.replace("\\", "/")
|
|
98
|
+
marker = "/tenants/"
|
|
99
|
+
if marker in normalized:
|
|
100
|
+
rest = normalized.split(marker, 1)[1]
|
|
101
|
+
return rest.split("/", 1)[0] or None
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _allowed_for_tenant(source: str, tenant_id: str | None) -> bool:
|
|
106
|
+
owned = _tenant_from_source(source)
|
|
107
|
+
if owned is None:
|
|
108
|
+
return True # shared knowledge
|
|
109
|
+
if tenant_id is None:
|
|
110
|
+
return False # hide all tenant-private docs without a scope
|
|
111
|
+
return owned == tenant_id
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def build_knowledge(
|
|
115
|
+
*,
|
|
116
|
+
enabled: bool,
|
|
117
|
+
paths: str | None,
|
|
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,
|
|
123
|
+
) -> KnowledgeStore | None:
|
|
124
|
+
if not enabled:
|
|
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
|
+
|
|
141
|
+
combined: list[str | Path] = []
|
|
142
|
+
if paths:
|
|
143
|
+
combined.extend(p.strip() for p in paths.split(",") if p.strip())
|
|
144
|
+
if adapter_docs:
|
|
145
|
+
combined.extend(adapter_docs)
|
|
146
|
+
if not combined:
|
|
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
|
+
|
|
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="
|
|
48
|
-
description="Safe API Agent — policy, dry-run, audit
|
|
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. [
|
|
272
|
-
5. [
|
|
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
|
-
- [
|
|
278
|
+
- [x] الحزمة منشورة: `pip install api-operator==1.0.0` — https://pypi.org/project/api-operator/1.0.0/
|
|
279
279
|
|
|
280
280
|
---
|
|
281
281
|
|
|
@@ -312,7 +312,7 @@ User message
|
|
|
312
312
|
**Done للمرحلة 2:**
|
|
313
313
|
- [x] التكامل opt-in (افتراضي آمن إن كان العامل معطّلًا).
|
|
314
314
|
- [x] الوثائق محدّثة في الكيت.
|
|
315
|
-
- [
|
|
315
|
+
- [x] إصدار tenant-kit patch يذكر دعم `api-operator>=0.11` (PR #36 → v1.5.3).
|
|
316
316
|
- [x] لا كسر لتثبيتات الكيت التي لا تستخدم الـ operator.
|
|
317
317
|
|
|
318
318
|
---
|
|
@@ -358,10 +358,11 @@ rag = ["pgvector...", "sqlalchemy..."] # يُحدد بدقة عند التنف
|
|
|
358
358
|
```
|
|
359
359
|
|
|
360
360
|
**Done للمرحلة 3:**
|
|
361
|
-
- [
|
|
362
|
-
- [
|
|
363
|
-
- [
|
|
364
|
-
- [
|
|
361
|
+
- [x] RAG معطّل افتراضيًا.
|
|
362
|
+
- [x] عزل tenant على مستوى الفهرس/الاستعلام.
|
|
363
|
+
- [x] مقاييس بسيطة: metadata.knowledge.hits / sources على الرد (تحسين اختيار الأداة يُقاس لاحقًا مع L1).
|
|
364
|
+
- [x] وثيقة `docs/knowledge.md`.
|
|
365
|
+
- [x] L1 embeddings + L2 pgvector retrieval (`api-operator[rag]`, إصدار 1.1.0).
|
|
365
366
|
|
|
366
367
|
---
|
|
367
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 = "
|
|
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,6 +35,13 @@ 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
46
|
|
|
40
47
|
[project.scripts]
|
|
@@ -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)
|
|
@@ -0,0 +1,81 @@
|
|
|
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.knowledge import KeywordKnowledge, build_knowledge, format_knowledge_context
|
|
10
|
+
from api_operator.adapters.mock import reset_mock_store
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.fixture(autouse=True)
|
|
14
|
+
def clean_store():
|
|
15
|
+
reset_mock_store()
|
|
16
|
+
yield
|
|
17
|
+
reset_mock_store()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_knowledge_disabled_by_default():
|
|
21
|
+
assert build_knowledge(enabled=False, paths="docs/a.md") is None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_tenant_isolation(tmp_path: Path):
|
|
25
|
+
shared = tmp_path / "shared.md"
|
|
26
|
+
shared.write_text(
|
|
27
|
+
"Workspace provisioning uses the create_workspace tool for new tenants.\n\n"
|
|
28
|
+
"More detail about shared platform policies for everyone.",
|
|
29
|
+
encoding="utf-8",
|
|
30
|
+
)
|
|
31
|
+
tenant_a = tmp_path / "tenants" / "acme" / "faq.md"
|
|
32
|
+
tenant_a.parent.mkdir(parents=True)
|
|
33
|
+
tenant_a.write_text(
|
|
34
|
+
"Acme private policy: always invite members with role admin for acme only.\n\n"
|
|
35
|
+
"Acme FAQ about workspace creation and billing quirks.",
|
|
36
|
+
encoding="utf-8",
|
|
37
|
+
)
|
|
38
|
+
tenant_b = tmp_path / "tenants" / "beta" / "faq.md"
|
|
39
|
+
tenant_b.parent.mkdir(parents=True)
|
|
40
|
+
tenant_b.write_text(
|
|
41
|
+
"Beta private secrets should never leak to other tenants in knowledge search.\n\n"
|
|
42
|
+
"Beta FAQ unrelated to acme workspace invites.",
|
|
43
|
+
encoding="utf-8",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
store = KeywordKnowledge([shared, tenant_a, tenant_b])
|
|
47
|
+
acme_hits = store.retrieve("workspace invite acme", tenant_id="acme", limit=5)
|
|
48
|
+
sources = {h.source for h in acme_hits}
|
|
49
|
+
assert str(shared) in sources or any("shared.md" in s for s in sources)
|
|
50
|
+
assert any("acme" in s.replace("\\", "/") for s in sources)
|
|
51
|
+
assert not any("/tenants/beta/" in s.replace("\\", "/") for s in sources)
|
|
52
|
+
|
|
53
|
+
no_scope = store.retrieve("Beta private secrets", tenant_id=None, limit=5)
|
|
54
|
+
assert all("/tenants/" not in h.source.replace("\\", "/") for h in no_scope)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_format_knowledge_context():
|
|
58
|
+
store_hits = KeywordKnowledge([]).retrieve("x")
|
|
59
|
+
assert format_knowledge_context(store_hits) == ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.asyncio
|
|
63
|
+
async def test_agent_injects_knowledge_metadata(tmp_path: Path):
|
|
64
|
+
doc = tmp_path / "guide.md"
|
|
65
|
+
doc.write_text(
|
|
66
|
+
"To list workspaces use the list_workspaces tool from the operator chat.\n\n"
|
|
67
|
+
"This paragraph explains workspace listing for the guided agent.",
|
|
68
|
+
encoding="utf-8",
|
|
69
|
+
)
|
|
70
|
+
agent = build_agent(
|
|
71
|
+
"mock",
|
|
72
|
+
settings=Settings(
|
|
73
|
+
planner="mock",
|
|
74
|
+
knowledge_enabled=True,
|
|
75
|
+
knowledge_paths=str(doc),
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
response = await agent.chat("list workspaces", abilities=["workspaces:read"])
|
|
79
|
+
assert response.status == "ok"
|
|
80
|
+
assert response.metadata.get("knowledge", {}).get("enabled") is True
|
|
81
|
+
assert response.metadata["knowledge"]["hits"] >= 1
|
|
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
|