api-operator 0.11.0__tar.gz → 1.0.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.0.0}/.env.example +3 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/CHANGELOG.md +14 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/PKG-INFO +6 -5
- {api_operator-0.11.0 → api_operator-1.0.0}/README.md +4 -3
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/__init__.py +1 -1
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/agent.py +74 -6
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/config.py +3 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/factory.py +3 -0
- api_operator-1.0.0/api_operator/rag/__init__.py +6 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/rag/indexer.py +2 -2
- api_operator-1.0.0/api_operator/rag/knowledge.py +129 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/server/app.py +2 -2
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/ROADMAP-vNEXT.md +9 -8
- api_operator-1.0.0/docs/knowledge.md +46 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/pyproject.toml +3 -2
- api_operator-1.0.0/tests/test_knowledge.py +81 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/.github/workflows/tests.yml +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/.gitignore +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/Dockerfile +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/LICENSE +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/__init__.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/base.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/mock.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/openapi_generator.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/registry.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/yaml_adapter.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/adapters/yaml_spec.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/audit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/executor.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/formatters.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/guardrails.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/memory.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/planner.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/planner_openai.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/quota.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/redaction.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/core/schemas.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/server/cli.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/tools/base.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/api_operator/tools/schema.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/audit.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/dry-run.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/policy.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/public-api-inventory.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/docs/quotas.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/jsonplaceholder-adapter/README.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/jsonplaceholder-adapter/adapter.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/jsonplaceholder-adapter/policy.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/tenant-kit-adapter/README.md +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/tenant-kit-adapter/adapter.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/examples/tenant-kit-adapter/policy.yaml +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/scripts/integration_tenant_kit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/__init__.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_agent.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_api.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_audit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_cli.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_core.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_dry_run.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_formatters.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_integration_tenant_kit.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_mock_adapter.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_openapi_policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_policy.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_quota.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_scenarios_e2e.py +0 -0
- {api_operator-0.11.0 → api_operator-1.0.0}/tests/test_yaml_adapter.py +0 -0
|
@@ -10,4 +10,7 @@ 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
|
|
13
16
|
# api_operator_CORS_ORIGINS=http://localhost:3000
|
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.0.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
**Safe API Agent** production label. Builds on 0.11 foundation; additive and backward compatible for existing adapters.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Opt-in **keyword knowledge (L0)**: `API_OPERATOR_KNOWLEDGE_ENABLED` + `KNOWLEDGE_PATHS`
|
|
12
|
+
- Tenant-scoped doc isolation under `/tenants/{id}/`
|
|
13
|
+
- `docs/knowledge.md` (L1+ `rag` extra deferred to 1.1.0)
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- Package version **1.0.0**; README / FastAPI metadata aligned
|
|
18
|
+
|
|
5
19
|
## [0.11.0] - 2026-11-23
|
|
6
20
|
|
|
7
21
|
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: 0.
|
|
4
|
-
Summary: Safe API Agent — run APIs with policy, quotas, and
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Safe API Agent — run APIs with policy, quotas, audit, and optional 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
|
|
@@ -51,9 +51,9 @@ Works with Laravel, Go, or any REST API. First-class example: [laravel-tenant-ki
|
|
|
51
51
|
## Install
|
|
52
52
|
|
|
53
53
|
```bash
|
|
54
|
-
pip install api-operator
|
|
54
|
+
pip install api-operator==1.0.0
|
|
55
55
|
# optional OpenAI planner
|
|
56
|
-
pip install "api-operator[llm]"
|
|
56
|
+
pip install "api-operator[llm]==1.0.0"
|
|
57
57
|
```
|
|
58
58
|
|
|
59
59
|
Development:
|
|
@@ -89,9 +89,10 @@ api-operator chat \
|
|
|
89
89
|
| Dry-run (`--dry-run` / `dry_run=true`) | OpenAPI specs |
|
|
90
90
|
| AuditSink + redaction | API tokens in `.env` |
|
|
91
91
|
| QuotaGateway hooks | Host billing (e.g. tenant-kit meters) |
|
|
92
|
+
| Optional keyword knowledge (L0) | Doc paths / per-tenant FAQ |
|
|
92
93
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
93
94
|
|
|
94
|
-
No hard dependency on Laravel, Postgres, or vector DBs.
|
|
95
|
+
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
95
96
|
|
|
96
97
|
## Safe by default
|
|
97
98
|
|
|
@@ -14,9 +14,9 @@ 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
|
|
17
|
+
pip install api-operator==1.0.0
|
|
18
18
|
# optional OpenAI planner
|
|
19
|
-
pip install "api-operator[llm]"
|
|
19
|
+
pip install "api-operator[llm]==1.0.0"
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
Development:
|
|
@@ -52,9 +52,10 @@ api-operator chat \
|
|
|
52
52
|
| Dry-run (`--dry-run` / `dry_run=true`) | OpenAPI specs |
|
|
53
53
|
| AuditSink + redaction | API tokens in `.env` |
|
|
54
54
|
| QuotaGateway hooks | Host billing (e.g. tenant-kit meters) |
|
|
55
|
+
| Optional keyword knowledge (L0) | Doc paths / per-tenant FAQ |
|
|
55
56
|
| `mock` + `yaml` adapters | Optional custom adapters |
|
|
56
57
|
|
|
57
|
-
No hard dependency on Laravel, Postgres, or vector DBs.
|
|
58
|
+
No hard dependency on Laravel, Postgres, or vector DBs. Knowledge is **off** until you enable it ([docs/knowledge.md](docs/knowledge.md)).
|
|
58
59
|
|
|
59
60
|
## Safe by default
|
|
60
61
|
|
|
@@ -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,15 @@ 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
|
+
)
|
|
108
|
+
|
|
94
109
|
async def chat(
|
|
95
110
|
self,
|
|
96
111
|
message: str,
|
|
@@ -135,33 +150,57 @@ class Agent:
|
|
|
135
150
|
session.add("assistant", reply, status="ok")
|
|
136
151
|
return AgentResponse(session_id=session.id, message=reply, status="ok")
|
|
137
152
|
|
|
153
|
+
system_prompt, knowledge_meta = self._system_prompt_with_knowledge(
|
|
154
|
+
message,
|
|
155
|
+
tenant_id=tenant_id,
|
|
156
|
+
)
|
|
138
157
|
plan = await self.planner.plan(
|
|
139
158
|
message=message,
|
|
140
159
|
registry=self.registry,
|
|
141
160
|
history=session.history(),
|
|
142
|
-
system_prompt=
|
|
161
|
+
system_prompt=system_prompt,
|
|
143
162
|
)
|
|
144
163
|
|
|
145
164
|
if plan.type == "respond":
|
|
146
165
|
session.add("assistant", plan.content, status="ok")
|
|
147
|
-
return AgentResponse(
|
|
166
|
+
return AgentResponse(
|
|
167
|
+
session_id=session.id,
|
|
168
|
+
message=plan.content,
|
|
169
|
+
status="ok",
|
|
170
|
+
metadata=knowledge_meta,
|
|
171
|
+
)
|
|
148
172
|
|
|
149
173
|
if plan.type == "clarify":
|
|
150
174
|
session.add("assistant", plan.content, status="ok")
|
|
151
|
-
return AgentResponse(
|
|
175
|
+
return AgentResponse(
|
|
176
|
+
session_id=session.id,
|
|
177
|
+
message=plan.content,
|
|
178
|
+
status="ok",
|
|
179
|
+
metadata=knowledge_meta,
|
|
180
|
+
)
|
|
152
181
|
|
|
153
182
|
if plan.type != "tool" or not plan.tool_name:
|
|
154
183
|
reply = "Could not determine an action."
|
|
155
184
|
session.add("assistant", reply, status="error")
|
|
156
|
-
return AgentResponse(
|
|
185
|
+
return AgentResponse(
|
|
186
|
+
session_id=session.id,
|
|
187
|
+
message=reply,
|
|
188
|
+
status="error",
|
|
189
|
+
metadata=knowledge_meta,
|
|
190
|
+
)
|
|
157
191
|
|
|
158
192
|
tool = self.registry.get(plan.tool_name)
|
|
159
193
|
if tool is None:
|
|
160
194
|
reply = f"Tool not found: {plan.tool_name}"
|
|
161
195
|
session.add("assistant", reply, status="error")
|
|
162
|
-
return AgentResponse(
|
|
196
|
+
return AgentResponse(
|
|
197
|
+
session_id=session.id,
|
|
198
|
+
message=reply,
|
|
199
|
+
status="error",
|
|
200
|
+
metadata=knowledge_meta,
|
|
201
|
+
)
|
|
163
202
|
|
|
164
|
-
|
|
203
|
+
response = await self._run_tool(
|
|
165
204
|
session,
|
|
166
205
|
plan.tool_name,
|
|
167
206
|
plan.tool_args or {},
|
|
@@ -169,6 +208,35 @@ class Agent:
|
|
|
169
208
|
skip_confirmation=auto_confirm,
|
|
170
209
|
dry_run=use_dry_run,
|
|
171
210
|
)
|
|
211
|
+
if knowledge_meta:
|
|
212
|
+
response.metadata = {**knowledge_meta, **response.metadata}
|
|
213
|
+
return response
|
|
214
|
+
|
|
215
|
+
def _system_prompt_with_knowledge(
|
|
216
|
+
self,
|
|
217
|
+
message: str,
|
|
218
|
+
*,
|
|
219
|
+
tenant_id: str | None,
|
|
220
|
+
) -> tuple[str, dict[str, Any]]:
|
|
221
|
+
base = self.adapter.system_prompt()
|
|
222
|
+
if self.knowledge is None:
|
|
223
|
+
return base, {}
|
|
224
|
+
hits = self.knowledge.retrieve(
|
|
225
|
+
message,
|
|
226
|
+
tenant_id=tenant_id,
|
|
227
|
+
limit=self.settings.knowledge_limit,
|
|
228
|
+
)
|
|
229
|
+
if not hits:
|
|
230
|
+
return base, {"knowledge": {"enabled": True, "hits": 0}}
|
|
231
|
+
block = format_knowledge_context(hits)
|
|
232
|
+
meta = {
|
|
233
|
+
"knowledge": {
|
|
234
|
+
"enabled": True,
|
|
235
|
+
"hits": len(hits),
|
|
236
|
+
"sources": [h.source for h in hits],
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return f"{base}\n\n{block}", meta
|
|
172
240
|
|
|
173
241
|
async def _run_tool(
|
|
174
242
|
self,
|
|
@@ -22,3 +22,6 @@ 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 keyword RAG (L0)
|
|
26
|
+
knowledge_paths: str | None = None # comma-separated doc paths
|
|
27
|
+
knowledge_limit: int = 3
|
|
@@ -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,6 @@
|
|
|
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"]
|
|
@@ -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,129 @@
|
|
|
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: int = 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=int(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
|
+
) -> KnowledgeStore | None:
|
|
120
|
+
if not enabled:
|
|
121
|
+
return None
|
|
122
|
+
combined: list[str | Path] = []
|
|
123
|
+
if paths:
|
|
124
|
+
combined.extend(p.strip() for p in paths.split(",") if p.strip())
|
|
125
|
+
if adapter_docs:
|
|
126
|
+
combined.extend(adapter_docs)
|
|
127
|
+
if not combined:
|
|
128
|
+
return None
|
|
129
|
+
return KeywordKnowledge(combined)
|
|
@@ -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="0.
|
|
48
|
-
description="Safe API Agent — policy, dry-run, audit
|
|
47
|
+
version="1.0.0",
|
|
48
|
+
description="Safe API Agent — policy, dry-run, audit, optional knowledge",
|
|
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==0.11.0` (Foundation؛ قفزة `1.0.0` لاحقًا عند الجاهزية).
|
|
272
|
+
5. [x] Tag Git `v0.11.0` (و`v1.0.0` عند الـ major).
|
|
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==0.11.0` — https://pypi.org/project/api-operator/0.11.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
|
+
- [ ] L1 embeddings + L2 pgvector (ما زال لـ 1.1.0 extra).
|
|
365
366
|
|
|
366
367
|
---
|
|
367
368
|
|
|
@@ -0,0 +1,46 @@
|
|
|
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.
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "api-operator"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Safe API Agent — run APIs with policy, quotas, and
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Safe API Agent — run APIs with policy, quotas, audit, and optional knowledge"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
11
11
|
license = "MIT"
|
|
@@ -36,6 +36,7 @@ dependencies = [
|
|
|
36
36
|
[project.optional-dependencies]
|
|
37
37
|
llm = ["openai>=1.35.0"]
|
|
38
38
|
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.
|
|
39
40
|
|
|
40
41
|
[project.scripts]
|
|
41
42
|
api-operator = "api_operator.server.cli:app"
|
|
@@ -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
|