remdb 0.2.6__py3-none-any.whl → 0.3.118__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of remdb might be problematic. Click here for more details.
- rem/__init__.py +129 -2
- rem/agentic/README.md +76 -0
- rem/agentic/__init__.py +15 -0
- rem/agentic/agents/__init__.py +16 -2
- rem/agentic/agents/sse_simulator.py +500 -0
- rem/agentic/context.py +28 -22
- rem/agentic/llm_provider_models.py +301 -0
- rem/agentic/mcp/tool_wrapper.py +29 -3
- rem/agentic/otel/setup.py +92 -4
- rem/agentic/providers/phoenix.py +32 -43
- rem/agentic/providers/pydantic_ai.py +168 -24
- rem/agentic/schema.py +358 -21
- rem/agentic/tools/rem_tools.py +3 -3
- rem/api/README.md +238 -1
- rem/api/deps.py +255 -0
- rem/api/main.py +154 -37
- rem/api/mcp_router/resources.py +1 -1
- rem/api/mcp_router/server.py +26 -5
- rem/api/mcp_router/tools.py +454 -7
- rem/api/middleware/tracking.py +172 -0
- rem/api/routers/admin.py +494 -0
- rem/api/routers/auth.py +124 -0
- rem/api/routers/chat/completions.py +152 -16
- rem/api/routers/chat/models.py +7 -3
- rem/api/routers/chat/sse_events.py +526 -0
- rem/api/routers/chat/streaming.py +608 -45
- rem/api/routers/dev.py +81 -0
- rem/api/routers/feedback.py +148 -0
- rem/api/routers/messages.py +473 -0
- rem/api/routers/models.py +78 -0
- rem/api/routers/query.py +360 -0
- rem/api/routers/shared_sessions.py +406 -0
- rem/auth/middleware.py +126 -27
- rem/cli/commands/README.md +237 -64
- rem/cli/commands/ask.py +15 -11
- rem/cli/commands/cluster.py +1300 -0
- rem/cli/commands/configure.py +170 -97
- rem/cli/commands/db.py +396 -139
- rem/cli/commands/experiments.py +278 -96
- rem/cli/commands/process.py +22 -15
- rem/cli/commands/scaffold.py +47 -0
- rem/cli/commands/schema.py +97 -50
- rem/cli/main.py +37 -6
- rem/config.py +2 -2
- rem/models/core/core_model.py +7 -1
- rem/models/core/rem_query.py +5 -2
- rem/models/entities/__init__.py +21 -0
- rem/models/entities/domain_resource.py +38 -0
- rem/models/entities/feedback.py +123 -0
- rem/models/entities/message.py +30 -1
- rem/models/entities/session.py +83 -0
- rem/models/entities/shared_session.py +180 -0
- rem/models/entities/user.py +10 -3
- rem/registry.py +373 -0
- rem/schemas/agents/rem.yaml +7 -3
- rem/services/content/providers.py +94 -140
- rem/services/content/service.py +115 -24
- rem/services/dreaming/affinity_service.py +2 -16
- rem/services/dreaming/moment_service.py +2 -15
- rem/services/embeddings/api.py +24 -17
- rem/services/embeddings/worker.py +16 -16
- rem/services/phoenix/EXPERIMENT_DESIGN.md +3 -3
- rem/services/phoenix/client.py +252 -19
- rem/services/postgres/README.md +159 -15
- rem/services/postgres/__init__.py +2 -1
- rem/services/postgres/diff_service.py +531 -0
- rem/services/postgres/pydantic_to_sqlalchemy.py +427 -129
- rem/services/postgres/repository.py +132 -0
- rem/services/postgres/schema_generator.py +291 -9
- rem/services/postgres/service.py +6 -6
- rem/services/rate_limit.py +113 -0
- rem/services/rem/README.md +14 -0
- rem/services/rem/parser.py +44 -9
- rem/services/rem/service.py +36 -2
- rem/services/session/compression.py +17 -1
- rem/services/session/reload.py +1 -1
- rem/services/user_service.py +98 -0
- rem/settings.py +169 -22
- rem/sql/background_indexes.sql +21 -16
- rem/sql/migrations/001_install.sql +387 -54
- rem/sql/migrations/002_install_models.sql +2320 -393
- rem/sql/migrations/003_optional_extensions.sql +326 -0
- rem/sql/migrations/004_cache_system.sql +548 -0
- rem/utils/__init__.py +18 -0
- rem/utils/constants.py +97 -0
- rem/utils/date_utils.py +228 -0
- rem/utils/embeddings.py +17 -4
- rem/utils/files.py +167 -0
- rem/utils/mime_types.py +158 -0
- rem/utils/model_helpers.py +156 -1
- rem/utils/schema_loader.py +284 -21
- rem/utils/sql_paths.py +146 -0
- rem/utils/sql_types.py +3 -1
- rem/utils/vision.py +9 -14
- rem/workers/README.md +14 -14
- rem/workers/__init__.py +2 -1
- rem/workers/db_maintainer.py +74 -0
- rem/workers/unlogged_maintainer.py +463 -0
- {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/METADATA +598 -171
- {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/RECORD +102 -73
- {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/WHEEL +1 -1
- rem/sql/002_install_models.sql +0 -1068
- rem/sql/install_models.sql +0 -1038
- {remdb-0.2.6.dist-info → remdb-0.3.118.dist-info}/entry_points.txt +0 -0
rem/utils/model_helpers.py
CHANGED
|
@@ -16,8 +16,12 @@ Embedding Field Detection:
|
|
|
16
16
|
Table Name Inference:
|
|
17
17
|
1. model_config.json_schema_extra.table_name
|
|
18
18
|
2. CamelCase → snake_case + pluralization
|
|
19
|
+
|
|
20
|
+
Model Resolution:
|
|
21
|
+
- model_from_arbitrary_casing: Resolve model class from flexible input casing
|
|
19
22
|
"""
|
|
20
23
|
|
|
24
|
+
import re
|
|
21
25
|
from typing import Any, Type
|
|
22
26
|
|
|
23
27
|
from loguru import logger
|
|
@@ -94,7 +98,9 @@ def get_table_name(model: Type[BaseModel]) -> str:
|
|
|
94
98
|
if isinstance(model_config, dict):
|
|
95
99
|
json_extra = model_config.get("json_schema_extra", {})
|
|
96
100
|
if isinstance(json_extra, dict) and "table_name" in json_extra:
|
|
97
|
-
|
|
101
|
+
table_name = json_extra["table_name"]
|
|
102
|
+
if isinstance(table_name, str):
|
|
103
|
+
return table_name
|
|
98
104
|
|
|
99
105
|
# Infer from class name
|
|
100
106
|
name = model.__name__
|
|
@@ -234,3 +240,152 @@ def get_model_metadata(model: Type[BaseModel]) -> dict[str, Any]:
|
|
|
234
240
|
"entity_key_field": get_entity_key_field(model),
|
|
235
241
|
"embeddable_fields": get_embeddable_fields(model),
|
|
236
242
|
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def normalize_to_title_case(name: str) -> str:
|
|
246
|
+
"""
|
|
247
|
+
Normalize arbitrary casing to TitleCase (PascalCase).
|
|
248
|
+
|
|
249
|
+
Handles various input formats:
|
|
250
|
+
- kebab-case: domain-resource → DomainResource
|
|
251
|
+
- snake_case: domain_resource → DomainResource
|
|
252
|
+
- lowercase: domainresource → Domainresource (single word)
|
|
253
|
+
- TitleCase: DomainResource → DomainResource (passthrough)
|
|
254
|
+
- Mixed: Domain-Resource, DOMAIN_RESOURCE → DomainResource
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
name: Input name in any casing format
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
TitleCase (PascalCase) version of the name
|
|
261
|
+
|
|
262
|
+
Example:
|
|
263
|
+
>>> normalize_to_title_case("domain-resource")
|
|
264
|
+
'DomainResource'
|
|
265
|
+
>>> normalize_to_title_case("domain_resources")
|
|
266
|
+
'DomainResources'
|
|
267
|
+
>>> normalize_to_title_case("DomainResource")
|
|
268
|
+
'DomainResource'
|
|
269
|
+
"""
|
|
270
|
+
# If already TitleCase (starts with uppercase, has no delimiters, and has
|
|
271
|
+
# at least one lowercase letter), return as-is
|
|
272
|
+
if (
|
|
273
|
+
name
|
|
274
|
+
and name[0].isupper()
|
|
275
|
+
and '-' not in name
|
|
276
|
+
and '_' not in name
|
|
277
|
+
and any(c.islower() for c in name)
|
|
278
|
+
):
|
|
279
|
+
return name
|
|
280
|
+
|
|
281
|
+
# Split on common delimiters (hyphen, underscore)
|
|
282
|
+
parts = re.split(r'[-_]', name)
|
|
283
|
+
|
|
284
|
+
# Capitalize first letter of each part, lowercase the rest
|
|
285
|
+
normalized_parts = [part.capitalize() for part in parts if part]
|
|
286
|
+
|
|
287
|
+
return "".join(normalized_parts)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def model_from_arbitrary_casing(
|
|
291
|
+
name: str,
|
|
292
|
+
registry: dict[str, Type[BaseModel]] | None = None,
|
|
293
|
+
) -> Type[BaseModel]:
|
|
294
|
+
"""
|
|
295
|
+
Resolve a model class from arbitrary casing input.
|
|
296
|
+
|
|
297
|
+
REM entity models use strict TitleCase (PascalCase) naming. This function
|
|
298
|
+
allows flexible input formats while maintaining consistency:
|
|
299
|
+
|
|
300
|
+
Input formats supported:
|
|
301
|
+
- kebab-case: domain-resource, domain-resources
|
|
302
|
+
- snake_case: domain_resource, domain_resources
|
|
303
|
+
- lowercase: resource, domainresource
|
|
304
|
+
- TitleCase: Resource, DomainResource
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
name: Model name in any supported casing format
|
|
308
|
+
registry: Optional dict mapping TitleCase names to model classes.
|
|
309
|
+
If not provided, uses rem.models.entities module.
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
The resolved Pydantic model class
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
ValueError: If no model matches the normalized name
|
|
316
|
+
|
|
317
|
+
Example:
|
|
318
|
+
>>> model = model_from_arbitrary_casing("domain-resources")
|
|
319
|
+
>>> model.__name__
|
|
320
|
+
'DomainResource'
|
|
321
|
+
>>> model = model_from_arbitrary_casing("Resource")
|
|
322
|
+
>>> model.__name__
|
|
323
|
+
'Resource'
|
|
324
|
+
"""
|
|
325
|
+
# Build default registry from entities module if not provided
|
|
326
|
+
if registry is None:
|
|
327
|
+
from rem.models.entities import (
|
|
328
|
+
DomainResource,
|
|
329
|
+
Feedback,
|
|
330
|
+
File,
|
|
331
|
+
ImageResource,
|
|
332
|
+
Message,
|
|
333
|
+
Moment,
|
|
334
|
+
Ontology,
|
|
335
|
+
OntologyConfig,
|
|
336
|
+
Resource,
|
|
337
|
+
Schema,
|
|
338
|
+
Session,
|
|
339
|
+
User,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
registry = {
|
|
343
|
+
"Resource": Resource,
|
|
344
|
+
"Resources": Resource, # Plural alias
|
|
345
|
+
"DomainResource": DomainResource,
|
|
346
|
+
"DomainResources": DomainResource, # Plural alias
|
|
347
|
+
"ImageResource": ImageResource,
|
|
348
|
+
"ImageResources": ImageResource,
|
|
349
|
+
"File": File,
|
|
350
|
+
"Files": File,
|
|
351
|
+
"Message": Message,
|
|
352
|
+
"Messages": Message,
|
|
353
|
+
"Moment": Moment,
|
|
354
|
+
"Moments": Moment,
|
|
355
|
+
"Session": Session,
|
|
356
|
+
"Sessions": Session,
|
|
357
|
+
"Feedback": Feedback,
|
|
358
|
+
"User": User,
|
|
359
|
+
"Users": User,
|
|
360
|
+
"Schema": Schema,
|
|
361
|
+
"Schemas": Schema,
|
|
362
|
+
"Ontology": Ontology,
|
|
363
|
+
"Ontologies": Ontology,
|
|
364
|
+
"OntologyConfig": OntologyConfig,
|
|
365
|
+
"OntologyConfigs": OntologyConfig,
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
# Normalize input to TitleCase
|
|
369
|
+
normalized = normalize_to_title_case(name)
|
|
370
|
+
|
|
371
|
+
# Look up in registry
|
|
372
|
+
if normalized in registry:
|
|
373
|
+
logger.debug(f"Resolved model '{name}' → {registry[normalized].__name__}")
|
|
374
|
+
return registry[normalized]
|
|
375
|
+
|
|
376
|
+
# Try without trailing 's' (singular form)
|
|
377
|
+
if normalized.endswith("s") and normalized[:-1] in registry:
|
|
378
|
+
logger.debug(f"Resolved model '{name}' → {registry[normalized[:-1]].__name__} (singular)")
|
|
379
|
+
return registry[normalized[:-1]]
|
|
380
|
+
|
|
381
|
+
# Try with trailing 's' (plural form)
|
|
382
|
+
plural = normalized + "s"
|
|
383
|
+
if plural in registry:
|
|
384
|
+
logger.debug(f"Resolved model '{name}' → {registry[plural].__name__} (plural)")
|
|
385
|
+
return registry[plural]
|
|
386
|
+
|
|
387
|
+
available = sorted(set(m.__name__ for m in registry.values()))
|
|
388
|
+
raise ValueError(
|
|
389
|
+
f"Unknown model: '{name}' (normalized: '{normalized}'). "
|
|
390
|
+
f"Available models: {', '.join(available)}"
|
|
391
|
+
)
|
rem/utils/schema_loader.py
CHANGED
|
@@ -9,7 +9,7 @@ Design Pattern:
|
|
|
9
9
|
- Support short names: "contract-analyzer" → "schemas/agents/contract-analyzer.yaml"
|
|
10
10
|
- Support relative/absolute paths
|
|
11
11
|
- Consistent error messages and logging
|
|
12
|
-
|
|
12
|
+
|
|
13
13
|
Usage:
|
|
14
14
|
# From API
|
|
15
15
|
schema = load_agent_schema("rem")
|
|
@@ -20,6 +20,26 @@ Usage:
|
|
|
20
20
|
# From agent factory
|
|
21
21
|
schema = load_agent_schema("contract-analyzer")
|
|
22
22
|
|
|
23
|
+
TODO: Git FS Integration
|
|
24
|
+
The schema loader currently uses importlib.resources for package schemas
|
|
25
|
+
and direct filesystem access for custom paths. The FS abstraction layer
|
|
26
|
+
(rem.services.fs.FS) could be used to abstract storage backends:
|
|
27
|
+
|
|
28
|
+
- Local filesystem (current)
|
|
29
|
+
- Git repositories (GitService)
|
|
30
|
+
- S3 (via FS provider)
|
|
31
|
+
|
|
32
|
+
This would enable loading schemas from versioned Git repos or S3 buckets
|
|
33
|
+
without changing the API. The FS provider pattern already exists and just
|
|
34
|
+
needs integration testing with the schema loader.
|
|
35
|
+
|
|
36
|
+
Example future usage:
|
|
37
|
+
# Load from Git at specific version
|
|
38
|
+
schema = load_agent_schema("git://rem/schemas/agents/rem.yaml?ref=v1.0.0")
|
|
39
|
+
|
|
40
|
+
# Load from S3
|
|
41
|
+
schema = load_agent_schema("s3://rem-schemas/agents/cv-parser.yaml")
|
|
42
|
+
|
|
23
43
|
Schema Caching Status:
|
|
24
44
|
|
|
25
45
|
✅ IMPLEMENTED: Filesystem Schema Caching (2025-11-22)
|
|
@@ -71,13 +91,14 @@ import yaml
|
|
|
71
91
|
from loguru import logger
|
|
72
92
|
|
|
73
93
|
|
|
74
|
-
# Standard search paths for agent schemas (in priority order)
|
|
94
|
+
# Standard search paths for agent/evaluator schemas (in priority order)
|
|
75
95
|
SCHEMA_SEARCH_PATHS = [
|
|
76
96
|
"schemas/agents/{name}.yaml", # Top-level agents (e.g., rem.yaml)
|
|
77
97
|
"schemas/agents/core/{name}.yaml", # Core system agents
|
|
78
98
|
"schemas/agents/examples/{name}.yaml", # Example agents
|
|
79
|
-
"schemas/evaluators/{name}.yaml",
|
|
80
|
-
"schemas/{name}.yaml",
|
|
99
|
+
"schemas/evaluators/{name}.yaml", # Nested evaluators (e.g., hello-world/default)
|
|
100
|
+
"schemas/evaluators/rem/{name}.yaml", # REM evaluators (e.g., lookup-correctness)
|
|
101
|
+
"schemas/{name}.yaml", # Generic schemas
|
|
81
102
|
]
|
|
82
103
|
|
|
83
104
|
# In-memory cache for filesystem schemas (no TTL - immutable)
|
|
@@ -89,10 +110,93 @@ _fs_schema_cache: dict[str, dict[str, Any]] = {}
|
|
|
89
110
|
# _db_schema_ttl: int = 300 # 5 minutes in seconds
|
|
90
111
|
|
|
91
112
|
|
|
92
|
-
def
|
|
113
|
+
def _load_schema_from_database(schema_name: str, user_id: str) -> dict[str, Any] | None:
|
|
114
|
+
"""
|
|
115
|
+
Load schema from database using LOOKUP query.
|
|
116
|
+
|
|
117
|
+
This function is synchronous but calls async database operations.
|
|
118
|
+
It's designed to be called from load_agent_schema() which is sync.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
schema_name: Schema name to lookup
|
|
122
|
+
user_id: User ID for data scoping
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
Schema spec (dict) if found, None otherwise
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
RuntimeError: If database connection fails
|
|
129
|
+
"""
|
|
130
|
+
import asyncio
|
|
131
|
+
|
|
132
|
+
# Check if we're already in an async context
|
|
133
|
+
try:
|
|
134
|
+
loop = asyncio.get_running_loop()
|
|
135
|
+
# We're in an async context - can't use asyncio.run()
|
|
136
|
+
# This shouldn't happen in normal usage since load_agent_schema is called from sync contexts
|
|
137
|
+
logger.warning(
|
|
138
|
+
"Database schema lookup called from async context. "
|
|
139
|
+
"This may cause issues. Consider using async version of load_agent_schema."
|
|
140
|
+
)
|
|
141
|
+
return None
|
|
142
|
+
except RuntimeError:
|
|
143
|
+
# Not in async context - safe to use asyncio.run()
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
async def _async_lookup():
|
|
147
|
+
"""Async helper to query database."""
|
|
148
|
+
from rem.services.postgres import get_postgres_service
|
|
149
|
+
|
|
150
|
+
db = get_postgres_service()
|
|
151
|
+
if not db:
|
|
152
|
+
logger.debug("PostgreSQL service not available for schema lookup")
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
await db.connect()
|
|
157
|
+
|
|
158
|
+
# Query schemas table directly by name
|
|
159
|
+
# Note: Schema name lookup is case-insensitive for user convenience
|
|
160
|
+
query = """
|
|
161
|
+
SELECT spec FROM schemas
|
|
162
|
+
WHERE LOWER(name) = LOWER($1)
|
|
163
|
+
AND (user_id = $2 OR user_id = 'system')
|
|
164
|
+
LIMIT 1
|
|
165
|
+
"""
|
|
166
|
+
logger.debug(f"Executing schema lookup: name={schema_name}, user_id={user_id}")
|
|
167
|
+
|
|
168
|
+
row = await db.fetchrow(query, schema_name, user_id)
|
|
169
|
+
|
|
170
|
+
if row:
|
|
171
|
+
spec = row.get("spec")
|
|
172
|
+
if spec and isinstance(spec, dict):
|
|
173
|
+
logger.debug(f"Found schema in database: {schema_name}")
|
|
174
|
+
return spec
|
|
175
|
+
|
|
176
|
+
logger.debug(f"Schema not found in database: {schema_name}")
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logger.debug(f"Database schema lookup error: {e}")
|
|
181
|
+
return None
|
|
182
|
+
finally:
|
|
183
|
+
await db.disconnect()
|
|
184
|
+
|
|
185
|
+
# Run async lookup in new event loop
|
|
186
|
+
return asyncio.run(_async_lookup())
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def load_agent_schema(
|
|
190
|
+
schema_name_or_path: str,
|
|
191
|
+
use_cache: bool = True,
|
|
192
|
+
user_id: str | None = None,
|
|
193
|
+
enable_db_fallback: bool = True,
|
|
194
|
+
) -> dict[str, Any]:
|
|
93
195
|
"""
|
|
94
196
|
Load agent schema from YAML file with unified search logic and caching.
|
|
95
197
|
|
|
198
|
+
Schema names are case-invariant - "Siggy", "siggy", "SIGGY" all resolve to the same schema.
|
|
199
|
+
|
|
96
200
|
Filesystem schemas are cached indefinitely (immutable, versioned with code).
|
|
97
201
|
Database schemas (future) will be cached with TTL for invalidation.
|
|
98
202
|
|
|
@@ -107,36 +211,43 @@ def load_agent_schema(schema_name_or_path: str, use_cache: bool = True) -> dict[
|
|
|
107
211
|
Search Order:
|
|
108
212
|
1. Check cache (if use_cache=True and schema found in FS cache)
|
|
109
213
|
2. Exact path if it exists (absolute or relative)
|
|
110
|
-
3.
|
|
111
|
-
4. Package resources: schemas/agents/
|
|
112
|
-
5. Package resources: schemas/agents/
|
|
113
|
-
6. Package resources: schemas/
|
|
114
|
-
7. Package resources: schemas/{name}.yaml
|
|
214
|
+
3. Custom paths from rem.register_schema_path() and SCHEMA__PATHS env var
|
|
215
|
+
4. Package resources: schemas/agents/{name}.yaml (top-level)
|
|
216
|
+
5. Package resources: schemas/agents/core/{name}.yaml
|
|
217
|
+
6. Package resources: schemas/agents/examples/{name}.yaml
|
|
218
|
+
7. Package resources: schemas/evaluators/{name}.yaml
|
|
219
|
+
8. Package resources: schemas/{name}.yaml
|
|
220
|
+
9. Database LOOKUP: schemas table (if enable_db_fallback=True and user_id provided)
|
|
115
221
|
|
|
116
222
|
Args:
|
|
117
|
-
schema_name_or_path: Schema name or file path
|
|
118
|
-
Examples: "rem-query-agent", "
|
|
223
|
+
schema_name_or_path: Schema name or file path (case-invariant for names)
|
|
224
|
+
Examples: "rem-query-agent", "Contract-Analyzer", "./my-schema.yaml"
|
|
119
225
|
use_cache: If True, uses in-memory cache for filesystem schemas
|
|
226
|
+
user_id: User ID for database schema lookup (required for DB fallback)
|
|
227
|
+
enable_db_fallback: If True, falls back to database LOOKUP when file not found
|
|
120
228
|
|
|
121
229
|
Returns:
|
|
122
230
|
Agent schema as dictionary
|
|
123
231
|
|
|
124
232
|
Raises:
|
|
125
|
-
FileNotFoundError: If schema not found in any search location
|
|
233
|
+
FileNotFoundError: If schema not found in any search location (filesystem + database)
|
|
126
234
|
yaml.YAMLError: If schema file is invalid YAML
|
|
127
235
|
|
|
128
236
|
Examples:
|
|
129
|
-
>>> # Load by short name (cached after first load)
|
|
130
|
-
>>> schema = load_agent_schema("contract-analyzer"
|
|
237
|
+
>>> # Load by short name (cached after first load) - case invariant
|
|
238
|
+
>>> schema = load_agent_schema("Contract-Analyzer") # same as "contract-analyzer"
|
|
131
239
|
>>>
|
|
132
240
|
>>> # Load from custom path (not cached - custom paths may change)
|
|
133
241
|
>>> schema = load_agent_schema("./my-agent.yaml")
|
|
134
242
|
>>>
|
|
135
243
|
>>> # Load evaluator schema (cached)
|
|
136
244
|
>>> schema = load_agent_schema("rem-lookup-correctness")
|
|
245
|
+
>>>
|
|
246
|
+
>>> # Load custom user schema from database (case invariant)
|
|
247
|
+
>>> schema = load_agent_schema("My-Agent", user_id="user-123") # same as "my-agent"
|
|
137
248
|
"""
|
|
138
|
-
# Normalize the name for cache key
|
|
139
|
-
cache_key = str(schema_name_or_path).replace('agents/', '').replace('schemas/', '').replace('evaluators/', '').replace('core/', '').replace('examples/', '')
|
|
249
|
+
# Normalize the name for cache key (lowercase for case-invariant lookups)
|
|
250
|
+
cache_key = str(schema_name_or_path).replace('agents/', '').replace('schemas/', '').replace('evaluators/', '').replace('core/', '').replace('examples/', '').lower()
|
|
140
251
|
if cache_key.endswith('.yaml') or cache_key.endswith('.yml'):
|
|
141
252
|
cache_key = cache_key.rsplit('.', 1)[0]
|
|
142
253
|
|
|
@@ -157,10 +268,31 @@ def load_agent_schema(schema_name_or_path: str, use_cache: bool = True) -> dict[
|
|
|
157
268
|
# Don't cache custom paths (they may change)
|
|
158
269
|
return cast(dict[str, Any], schema)
|
|
159
270
|
|
|
160
|
-
# 2. Normalize name for package resource search
|
|
271
|
+
# 2. Normalize name for package resource search (lowercase)
|
|
161
272
|
base_name = cache_key
|
|
162
273
|
|
|
163
|
-
# 3. Try
|
|
274
|
+
# 3. Try custom schema paths (from registry + SCHEMA__PATHS env var)
|
|
275
|
+
from ..registry import get_schema_paths
|
|
276
|
+
|
|
277
|
+
custom_paths = get_schema_paths()
|
|
278
|
+
for custom_dir in custom_paths:
|
|
279
|
+
# Try various patterns within each custom directory
|
|
280
|
+
for pattern in [
|
|
281
|
+
f"{base_name}.yaml",
|
|
282
|
+
f"{base_name}.yml",
|
|
283
|
+
f"agents/{base_name}.yaml",
|
|
284
|
+
f"evaluators/{base_name}.yaml",
|
|
285
|
+
]:
|
|
286
|
+
custom_path = Path(custom_dir) / pattern
|
|
287
|
+
if custom_path.exists():
|
|
288
|
+
logger.debug(f"Loading schema from custom path: {custom_path}")
|
|
289
|
+
with open(custom_path, "r") as f:
|
|
290
|
+
schema = yaml.safe_load(f)
|
|
291
|
+
logger.debug(f"Loaded schema with keys: {list(schema.keys())}")
|
|
292
|
+
# Don't cache custom paths (they may change during development)
|
|
293
|
+
return cast(dict[str, Any], schema)
|
|
294
|
+
|
|
295
|
+
# 4. Try package resources with standard search paths
|
|
164
296
|
for search_pattern in SCHEMA_SEARCH_PATHS:
|
|
165
297
|
search_path = search_pattern.format(name=base_name)
|
|
166
298
|
|
|
@@ -185,16 +317,147 @@ def load_agent_schema(schema_name_or_path: str, use_cache: bool = True) -> dict[
|
|
|
185
317
|
logger.debug(f"Could not load from {search_path}: {e}")
|
|
186
318
|
continue
|
|
187
319
|
|
|
188
|
-
#
|
|
320
|
+
# 5. Try database LOOKUP fallback (if enabled and user_id provided)
|
|
321
|
+
if enable_db_fallback and user_id:
|
|
322
|
+
try:
|
|
323
|
+
logger.debug(f"Attempting database LOOKUP for schema: {base_name} (user_id={user_id})")
|
|
324
|
+
db_schema = _load_schema_from_database(base_name, user_id)
|
|
325
|
+
if db_schema:
|
|
326
|
+
logger.info(f"✅ Loaded schema from database: {base_name} (user_id={user_id})")
|
|
327
|
+
return db_schema
|
|
328
|
+
except Exception as e:
|
|
329
|
+
logger.debug(f"Database schema lookup failed: {e}")
|
|
330
|
+
# Fall through to error below
|
|
331
|
+
|
|
332
|
+
# 6. Schema not found in any location
|
|
189
333
|
searched_paths = [pattern.format(name=base_name) for pattern in SCHEMA_SEARCH_PATHS]
|
|
334
|
+
|
|
335
|
+
custom_paths_note = ""
|
|
336
|
+
if custom_paths:
|
|
337
|
+
custom_paths_note = f"\n - Custom paths: {', '.join(custom_paths)}"
|
|
338
|
+
|
|
339
|
+
db_search_note = ""
|
|
340
|
+
if enable_db_fallback:
|
|
341
|
+
if user_id:
|
|
342
|
+
db_search_note = f"\n - Database: LOOKUP '{base_name}' FROM schemas WHERE user_id='{user_id}' (no match)"
|
|
343
|
+
else:
|
|
344
|
+
db_search_note = "\n - Database: (skipped - no user_id provided)"
|
|
345
|
+
|
|
190
346
|
raise FileNotFoundError(
|
|
191
347
|
f"Schema not found: {schema_name_or_path}\n"
|
|
192
348
|
f"Searched locations:\n"
|
|
193
|
-
f" - Exact path: {path}
|
|
349
|
+
f" - Exact path: {path}"
|
|
350
|
+
f"{custom_paths_note}\n"
|
|
194
351
|
f" - Package resources: {', '.join(searched_paths)}"
|
|
352
|
+
f"{db_search_note}"
|
|
195
353
|
)
|
|
196
354
|
|
|
197
355
|
|
|
356
|
+
async def load_agent_schema_async(
|
|
357
|
+
schema_name_or_path: str,
|
|
358
|
+
user_id: str | None = None,
|
|
359
|
+
db=None,
|
|
360
|
+
) -> dict[str, Any]:
|
|
361
|
+
"""
|
|
362
|
+
Async version of load_agent_schema for use in async contexts.
|
|
363
|
+
|
|
364
|
+
Schema names are case-invariant - "MyAgent", "myagent", "MYAGENT" all resolve to the same schema.
|
|
365
|
+
|
|
366
|
+
This version accepts an existing database connection to avoid creating new connections.
|
|
367
|
+
|
|
368
|
+
Args:
|
|
369
|
+
schema_name_or_path: Schema name or file path (case-invariant for names)
|
|
370
|
+
user_id: User ID for database schema lookup
|
|
371
|
+
db: Optional existing PostgresService connection (if None, will create one)
|
|
372
|
+
|
|
373
|
+
Returns:
|
|
374
|
+
Agent schema as dictionary
|
|
375
|
+
|
|
376
|
+
Raises:
|
|
377
|
+
FileNotFoundError: If schema not found
|
|
378
|
+
"""
|
|
379
|
+
# First try filesystem search (sync operations are fine)
|
|
380
|
+
path = Path(schema_name_or_path)
|
|
381
|
+
|
|
382
|
+
# Normalize the name for cache key (lowercase for case-invariant lookups)
|
|
383
|
+
cache_key = str(schema_name_or_path).replace('agents/', '').replace('schemas/', '').replace('evaluators/', '').replace('core/', '').replace('examples/', '').lower()
|
|
384
|
+
if cache_key.endswith('.yaml') or cache_key.endswith('.yml'):
|
|
385
|
+
cache_key = cache_key.rsplit('.', 1)[0]
|
|
386
|
+
|
|
387
|
+
is_custom_path = path.exists() or '/' in str(schema_name_or_path) or '\\' in str(schema_name_or_path)
|
|
388
|
+
|
|
389
|
+
# Check cache
|
|
390
|
+
if not is_custom_path and cache_key in _fs_schema_cache:
|
|
391
|
+
logger.debug(f"Loading schema from cache: {cache_key}")
|
|
392
|
+
return _fs_schema_cache[cache_key]
|
|
393
|
+
|
|
394
|
+
# Try exact path
|
|
395
|
+
if path.exists():
|
|
396
|
+
logger.debug(f"Loading schema from exact path: {path}")
|
|
397
|
+
with open(path, "r") as f:
|
|
398
|
+
schema = yaml.safe_load(f)
|
|
399
|
+
return cast(dict[str, Any], schema)
|
|
400
|
+
|
|
401
|
+
base_name = cache_key
|
|
402
|
+
|
|
403
|
+
# Try custom schema paths
|
|
404
|
+
from ..registry import get_schema_paths
|
|
405
|
+
custom_paths = get_schema_paths()
|
|
406
|
+
for custom_dir in custom_paths:
|
|
407
|
+
for pattern in [f"{base_name}.yaml", f"{base_name}.yml", f"agents/{base_name}.yaml"]:
|
|
408
|
+
custom_path = Path(custom_dir) / pattern
|
|
409
|
+
if custom_path.exists():
|
|
410
|
+
with open(custom_path, "r") as f:
|
|
411
|
+
schema = yaml.safe_load(f)
|
|
412
|
+
return cast(dict[str, Any], schema)
|
|
413
|
+
|
|
414
|
+
# Try package resources
|
|
415
|
+
for search_pattern in SCHEMA_SEARCH_PATHS:
|
|
416
|
+
search_path = search_pattern.format(name=base_name)
|
|
417
|
+
try:
|
|
418
|
+
schema_ref = importlib.resources.files("rem") / search_path
|
|
419
|
+
schema_path = Path(str(schema_ref))
|
|
420
|
+
if schema_path.exists():
|
|
421
|
+
with open(schema_path, "r") as f:
|
|
422
|
+
schema = yaml.safe_load(f)
|
|
423
|
+
_fs_schema_cache[cache_key] = schema
|
|
424
|
+
return cast(dict[str, Any], schema)
|
|
425
|
+
except Exception:
|
|
426
|
+
continue
|
|
427
|
+
|
|
428
|
+
# Try database lookup
|
|
429
|
+
if user_id:
|
|
430
|
+
from rem.services.postgres import get_postgres_service
|
|
431
|
+
|
|
432
|
+
should_disconnect = False
|
|
433
|
+
if db is None:
|
|
434
|
+
db = get_postgres_service()
|
|
435
|
+
if db:
|
|
436
|
+
await db.connect()
|
|
437
|
+
should_disconnect = True
|
|
438
|
+
|
|
439
|
+
if db:
|
|
440
|
+
try:
|
|
441
|
+
query = """
|
|
442
|
+
SELECT spec FROM schemas
|
|
443
|
+
WHERE LOWER(name) = LOWER($1)
|
|
444
|
+
AND (user_id = $2 OR user_id = 'system' OR user_id IS NULL)
|
|
445
|
+
LIMIT 1
|
|
446
|
+
"""
|
|
447
|
+
row = await db.fetchrow(query, base_name, user_id)
|
|
448
|
+
if row:
|
|
449
|
+
spec = row.get("spec")
|
|
450
|
+
if spec and isinstance(spec, dict):
|
|
451
|
+
logger.info(f"✅ Loaded schema from database: {base_name}")
|
|
452
|
+
return spec
|
|
453
|
+
finally:
|
|
454
|
+
if should_disconnect:
|
|
455
|
+
await db.disconnect()
|
|
456
|
+
|
|
457
|
+
# Not found
|
|
458
|
+
raise FileNotFoundError(f"Schema not found: {schema_name_or_path}")
|
|
459
|
+
|
|
460
|
+
|
|
198
461
|
def validate_agent_schema(schema: dict[str, Any]) -> bool:
|
|
199
462
|
"""
|
|
200
463
|
Validate agent schema structure.
|