remdb 0.3.171__py3-none-any.whl → 0.3.230__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.
- rem/agentic/README.md +36 -2
- rem/agentic/context.py +173 -0
- rem/agentic/context_builder.py +12 -2
- rem/agentic/mcp/tool_wrapper.py +39 -16
- rem/agentic/providers/pydantic_ai.py +78 -45
- rem/agentic/schema.py +6 -5
- rem/agentic/tools/rem_tools.py +11 -0
- rem/api/main.py +1 -1
- rem/api/mcp_router/resources.py +75 -14
- rem/api/mcp_router/server.py +31 -24
- rem/api/mcp_router/tools.py +621 -166
- rem/api/routers/admin.py +30 -4
- rem/api/routers/auth.py +114 -15
- rem/api/routers/chat/child_streaming.py +379 -0
- rem/api/routers/chat/completions.py +74 -37
- rem/api/routers/chat/sse_events.py +7 -3
- rem/api/routers/chat/streaming.py +352 -257
- rem/api/routers/chat/streaming_utils.py +327 -0
- rem/api/routers/common.py +18 -0
- rem/api/routers/dev.py +7 -1
- rem/api/routers/feedback.py +9 -1
- rem/api/routers/messages.py +176 -38
- rem/api/routers/models.py +9 -1
- rem/api/routers/query.py +12 -1
- rem/api/routers/shared_sessions.py +16 -0
- rem/auth/jwt.py +19 -4
- rem/auth/middleware.py +42 -28
- rem/cli/README.md +62 -0
- rem/cli/commands/ask.py +61 -81
- rem/cli/commands/db.py +148 -70
- rem/cli/commands/process.py +171 -43
- rem/models/entities/ontology.py +91 -101
- rem/schemas/agents/rem.yaml +1 -1
- rem/services/content/service.py +18 -5
- rem/services/email/service.py +11 -2
- rem/services/embeddings/worker.py +26 -12
- rem/services/postgres/__init__.py +28 -3
- rem/services/postgres/diff_service.py +57 -5
- rem/services/postgres/programmable_diff_service.py +635 -0
- rem/services/postgres/pydantic_to_sqlalchemy.py +2 -2
- rem/services/postgres/register_type.py +12 -11
- rem/services/postgres/repository.py +39 -29
- rem/services/postgres/schema_generator.py +5 -5
- rem/services/postgres/sql_builder.py +6 -5
- rem/services/session/__init__.py +8 -1
- rem/services/session/compression.py +40 -2
- rem/services/session/pydantic_messages.py +292 -0
- rem/settings.py +34 -0
- rem/sql/background_indexes.sql +5 -0
- rem/sql/migrations/001_install.sql +157 -10
- rem/sql/migrations/002_install_models.sql +160 -132
- rem/sql/migrations/004_cache_system.sql +7 -275
- rem/sql/migrations/migrate_session_id_to_uuid.sql +45 -0
- rem/utils/model_helpers.py +101 -0
- rem/utils/schema_loader.py +79 -51
- {remdb-0.3.171.dist-info → remdb-0.3.230.dist-info}/METADATA +2 -2
- {remdb-0.3.171.dist-info → remdb-0.3.230.dist-info}/RECORD +59 -53
- {remdb-0.3.171.dist-info → remdb-0.3.230.dist-info}/WHEEL +0 -0
- {remdb-0.3.171.dist-info → remdb-0.3.230.dist-info}/entry_points.txt +0 -0
|
@@ -94,14 +94,14 @@ def generate_table_schema(
|
|
|
94
94
|
# Always add id as primary key
|
|
95
95
|
columns.append("id UUID PRIMARY KEY DEFAULT uuid_generate_v4()")
|
|
96
96
|
|
|
97
|
-
# Add tenant_id if tenant scoped
|
|
97
|
+
# Add tenant_id if tenant scoped (nullable - NULL means public/shared)
|
|
98
98
|
if tenant_scoped:
|
|
99
|
-
columns.append("tenant_id VARCHAR(100)
|
|
100
|
-
indexes.append(f"CREATE INDEX idx_{table_name}_tenant ON {table_name} (tenant_id);")
|
|
99
|
+
columns.append("tenant_id VARCHAR(100)")
|
|
100
|
+
indexes.append(f"CREATE INDEX IF NOT EXISTS idx_{table_name}_tenant ON {table_name} (tenant_id);")
|
|
101
101
|
|
|
102
102
|
# Add user_id (owner field)
|
|
103
103
|
columns.append("user_id VARCHAR(256)")
|
|
104
|
-
indexes.append(f"CREATE INDEX idx_{table_name}_user ON {table_name} (user_id);")
|
|
104
|
+
indexes.append(f"CREATE INDEX IF NOT EXISTS idx_{table_name}_user ON {table_name} (user_id);")
|
|
105
105
|
|
|
106
106
|
# Process Pydantic fields (skip system fields)
|
|
107
107
|
for field_name, field_info in model.model_fields.items():
|
|
@@ -125,19 +125,19 @@ def generate_table_schema(
|
|
|
125
125
|
# Add graph_edges JSONB field
|
|
126
126
|
columns.append("graph_edges JSONB DEFAULT '[]'::jsonb")
|
|
127
127
|
indexes.append(
|
|
128
|
-
f"CREATE INDEX idx_{table_name}_graph_edges ON {table_name} USING GIN (graph_edges);"
|
|
128
|
+
f"CREATE INDEX IF NOT EXISTS idx_{table_name}_graph_edges ON {table_name} USING GIN (graph_edges);"
|
|
129
129
|
)
|
|
130
130
|
|
|
131
131
|
# Add metadata JSONB field
|
|
132
132
|
columns.append("metadata JSONB DEFAULT '{}'::jsonb")
|
|
133
133
|
indexes.append(
|
|
134
|
-
f"CREATE INDEX idx_{table_name}_metadata ON {table_name} USING GIN (metadata);"
|
|
134
|
+
f"CREATE INDEX IF NOT EXISTS idx_{table_name}_metadata ON {table_name} USING GIN (metadata);"
|
|
135
135
|
)
|
|
136
136
|
|
|
137
137
|
# Add tags field (TEXT[] for list[str])
|
|
138
138
|
columns.append("tags TEXT[] DEFAULT ARRAY[]::TEXT[]")
|
|
139
139
|
indexes.append(
|
|
140
|
-
f"CREATE INDEX idx_{table_name}_tags ON {table_name} USING GIN (tags);"
|
|
140
|
+
f"CREATE INDEX IF NOT EXISTS idx_{table_name}_tags ON {table_name} USING GIN (tags);"
|
|
141
141
|
)
|
|
142
142
|
|
|
143
143
|
# Generate CREATE TABLE statement
|
|
@@ -202,10 +202,10 @@ CREATE TABLE IF NOT EXISTS {embeddings_table} (
|
|
|
202
202
|
);
|
|
203
203
|
|
|
204
204
|
-- Index for entity lookup (get all embeddings for entity)
|
|
205
|
-
CREATE INDEX idx_{embeddings_table}_entity ON {embeddings_table} (entity_id);
|
|
205
|
+
CREATE INDEX IF NOT EXISTS idx_{embeddings_table}_entity ON {embeddings_table} (entity_id);
|
|
206
206
|
|
|
207
207
|
-- Index for field + provider lookup
|
|
208
|
-
CREATE INDEX idx_{embeddings_table}_field_provider ON {embeddings_table} (field_name, provider);
|
|
208
|
+
CREATE INDEX IF NOT EXISTS idx_{embeddings_table}_field_provider ON {embeddings_table} (field_name, provider);
|
|
209
209
|
|
|
210
210
|
-- HNSW index for vector similarity search (created in background)
|
|
211
211
|
-- Note: This will be created by background thread after data load
|
|
@@ -258,6 +258,7 @@ BEGIN
|
|
|
258
258
|
RETURN OLD;
|
|
259
259
|
ELSIF (TG_OP = 'INSERT' OR TG_OP = 'UPDATE') THEN
|
|
260
260
|
-- Upsert to KV_STORE (O(1) lookup by entity_key)
|
|
261
|
+
-- tenant_id can be NULL (meaning public/shared data)
|
|
261
262
|
INSERT INTO kv_store (
|
|
262
263
|
entity_key,
|
|
263
264
|
entity_type,
|
|
@@ -268,7 +269,7 @@ BEGIN
|
|
|
268
269
|
graph_edges,
|
|
269
270
|
updated_at
|
|
270
271
|
) VALUES (
|
|
271
|
-
NEW.{entity_key_field}::VARCHAR,
|
|
272
|
+
normalize_key(NEW.{entity_key_field}::VARCHAR),
|
|
272
273
|
'{table_name}',
|
|
273
274
|
NEW.id,
|
|
274
275
|
NEW.tenant_id,
|
|
@@ -277,7 +278,7 @@ BEGIN
|
|
|
277
278
|
COALESCE(NEW.graph_edges, '[]'::jsonb),
|
|
278
279
|
CURRENT_TIMESTAMP
|
|
279
280
|
)
|
|
280
|
-
ON CONFLICT (tenant_id, entity_key)
|
|
281
|
+
ON CONFLICT (COALESCE(tenant_id, ''), entity_key)
|
|
281
282
|
DO UPDATE SET
|
|
282
283
|
entity_id = EXCLUDED.entity_id,
|
|
283
284
|
user_id = EXCLUDED.user_id,
|
|
@@ -25,7 +25,6 @@ from .sql_builder import (
|
|
|
25
25
|
build_select,
|
|
26
26
|
build_upsert,
|
|
27
27
|
)
|
|
28
|
-
from ...settings import settings
|
|
29
28
|
|
|
30
29
|
if TYPE_CHECKING:
|
|
31
30
|
from .service import PostgresService
|
|
@@ -33,15 +32,15 @@ if TYPE_CHECKING:
|
|
|
33
32
|
|
|
34
33
|
def get_postgres_service() -> "PostgresService | None":
|
|
35
34
|
"""
|
|
36
|
-
Get PostgresService
|
|
35
|
+
Get PostgresService singleton from parent module.
|
|
37
36
|
|
|
38
|
-
|
|
37
|
+
Uses late import to avoid circular import issues.
|
|
38
|
+
Previously had a separate _postgres_instance here which caused
|
|
39
|
+
"pool not connected" errors due to duplicate connection pools.
|
|
39
40
|
"""
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
from .service import PostgresService
|
|
44
|
-
return PostgresService()
|
|
41
|
+
# Late import to avoid circular import (repository.py imported by __init__.py)
|
|
42
|
+
from rem.services.postgres import get_postgres_service as _get_singleton
|
|
43
|
+
return _get_singleton()
|
|
45
44
|
|
|
46
45
|
T = TypeVar("T", bound=BaseModel)
|
|
47
46
|
|
|
@@ -74,7 +73,7 @@ class Repository(Generic[T]):
|
|
|
74
73
|
self,
|
|
75
74
|
records: T | list[T],
|
|
76
75
|
embeddable_fields: list[str] | None = None,
|
|
77
|
-
generate_embeddings: bool =
|
|
76
|
+
generate_embeddings: bool = True,
|
|
78
77
|
) -> T | list[T]:
|
|
79
78
|
"""
|
|
80
79
|
Upsert single record or list of records (create or update on ID conflict).
|
|
@@ -84,8 +83,9 @@ class Repository(Generic[T]):
|
|
|
84
83
|
|
|
85
84
|
Args:
|
|
86
85
|
records: Single model instance or list of model instances
|
|
87
|
-
embeddable_fields: Optional list of fields to generate embeddings for
|
|
88
|
-
|
|
86
|
+
embeddable_fields: Optional list of fields to generate embeddings for.
|
|
87
|
+
If None, auto-detects 'content' field if present.
|
|
88
|
+
generate_embeddings: Whether to queue embedding generation tasks (default: True)
|
|
89
89
|
|
|
90
90
|
Returns:
|
|
91
91
|
Single record or list of records with generated IDs (matches input type)
|
|
@@ -118,25 +118,35 @@ class Repository(Generic[T]):
|
|
|
118
118
|
record.id = row["id"] # type: ignore[attr-defined]
|
|
119
119
|
|
|
120
120
|
# Queue embedding generation if requested and worker is available
|
|
121
|
-
if generate_embeddings and
|
|
121
|
+
if generate_embeddings and self.db.embedding_worker:
|
|
122
122
|
from rem.services.embeddings import EmbeddingTask
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
123
|
+
from .register_type import should_embed_field
|
|
124
|
+
|
|
125
|
+
# Auto-detect embeddable fields if not specified
|
|
126
|
+
if embeddable_fields is None:
|
|
127
|
+
embeddable_fields = [
|
|
128
|
+
field_name
|
|
129
|
+
for field_name, field_info in self.model_class.model_fields.items()
|
|
130
|
+
if should_embed_field(field_name, field_info)
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
if embeddable_fields:
|
|
134
|
+
for record in records_list:
|
|
135
|
+
for field_name in embeddable_fields:
|
|
136
|
+
content = getattr(record, field_name, None)
|
|
137
|
+
if content and isinstance(content, str):
|
|
138
|
+
task = EmbeddingTask(
|
|
139
|
+
task_id=f"{record.id}-{field_name}", # type: ignore[attr-defined]
|
|
140
|
+
entity_id=str(record.id), # type: ignore[attr-defined]
|
|
141
|
+
table_name=self.table_name,
|
|
142
|
+
field_name=field_name,
|
|
143
|
+
content=content,
|
|
144
|
+
provider="openai", # Default provider
|
|
145
|
+
model="text-embedding-3-small", # Default model
|
|
146
|
+
)
|
|
147
|
+
await self.db.embedding_worker.queue_task(task)
|
|
148
|
+
|
|
149
|
+
logger.debug(f"Queued {len(records_list) * len(embeddable_fields)} embedding tasks")
|
|
140
150
|
|
|
141
151
|
# Return single item or list to match input type
|
|
142
152
|
return records_list[0] if is_single else records_list
|
|
@@ -351,10 +351,10 @@ class SchemaGenerator:
|
|
|
351
351
|
|
|
352
352
|
Priority:
|
|
353
353
|
1. Field with json_schema_extra={\"entity_key\": True}
|
|
354
|
-
2. Field named \"name\"
|
|
354
|
+
2. Field named \"name\" (human-readable identifier)
|
|
355
355
|
3. Field named \"key\"
|
|
356
|
-
4. Field named \"
|
|
357
|
-
5.
|
|
356
|
+
4. Field named \"uri\"
|
|
357
|
+
5. Field named \"id\" (fallback)
|
|
358
358
|
|
|
359
359
|
Args:
|
|
360
360
|
model: Pydantic model class
|
|
@@ -369,9 +369,9 @@ class SchemaGenerator:
|
|
|
369
369
|
if json_extra.get("entity_key"):
|
|
370
370
|
return field_name
|
|
371
371
|
|
|
372
|
-
# Check for key fields in priority order:
|
|
372
|
+
# Check for key fields in priority order: name -> key -> uri -> id
|
|
373
373
|
# (matching sql_builder.get_entity_key convention)
|
|
374
|
-
for candidate in ["
|
|
374
|
+
for candidate in ["name", "key", "uri", "id"]:
|
|
375
375
|
if candidate in model.model_fields:
|
|
376
376
|
return candidate
|
|
377
377
|
|
|
@@ -35,10 +35,11 @@ def get_natural_key(model: BaseModel) -> str | None:
|
|
|
35
35
|
|
|
36
36
|
def get_entity_key(model: BaseModel) -> str:
|
|
37
37
|
"""
|
|
38
|
-
Get entity key for KV store following precedence:
|
|
38
|
+
Get entity key for KV store following precedence: name -> key -> uri -> id.
|
|
39
39
|
|
|
40
|
-
For KV store lookups, we prefer
|
|
41
|
-
then
|
|
40
|
+
For KV store lookups, we prefer human-readable identifiers first (name/key),
|
|
41
|
+
then URIs, with id as the fallback. This allows users to lookup entities
|
|
42
|
+
by their natural names like "panic-disorder" instead of UUIDs.
|
|
42
43
|
|
|
43
44
|
Args:
|
|
44
45
|
model: Pydantic model instance
|
|
@@ -46,13 +47,13 @@ def get_entity_key(model: BaseModel) -> str:
|
|
|
46
47
|
Returns:
|
|
47
48
|
Entity key string (guaranteed to exist)
|
|
48
49
|
"""
|
|
49
|
-
for field in ["
|
|
50
|
+
for field in ["name", "key", "uri", "id"]:
|
|
50
51
|
if hasattr(model, field):
|
|
51
52
|
value = getattr(model, field)
|
|
52
53
|
if value:
|
|
53
54
|
return str(value)
|
|
54
55
|
# Should never reach here since id always exists in CoreModel
|
|
55
|
-
raise ValueError(f"Model {type(model)} has no
|
|
56
|
+
raise ValueError(f"Model {type(model)} has no name, key, uri, or id field")
|
|
56
57
|
|
|
57
58
|
|
|
58
59
|
def generate_deterministic_id(user_id: str | None, entity_key: str) -> uuid.UUID:
|
rem/services/session/__init__.py
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
"""Session management services for conversation persistence and compression."""
|
|
2
2
|
|
|
3
3
|
from .compression import MessageCompressor, SessionMessageStore
|
|
4
|
+
from .pydantic_messages import audit_session_history, session_to_pydantic_messages
|
|
4
5
|
from .reload import reload_session
|
|
5
6
|
|
|
6
|
-
__all__ = [
|
|
7
|
+
__all__ = [
|
|
8
|
+
"MessageCompressor",
|
|
9
|
+
"SessionMessageStore",
|
|
10
|
+
"audit_session_history",
|
|
11
|
+
"reload_session",
|
|
12
|
+
"session_to_pydantic_messages",
|
|
13
|
+
]
|
|
@@ -65,7 +65,7 @@ def truncate_key(key: str, max_length: int = MAX_ENTITY_KEY_LENGTH) -> str:
|
|
|
65
65
|
logger.warning(f"Truncated key from {len(key)} to {len(truncated)} chars: {key[:50]}...")
|
|
66
66
|
return truncated
|
|
67
67
|
|
|
68
|
-
from rem.models.entities import Message
|
|
68
|
+
from rem.models.entities import Message, Session
|
|
69
69
|
from rem.services.postgres import PostgresService, Repository
|
|
70
70
|
from rem.settings import settings
|
|
71
71
|
|
|
@@ -177,6 +177,39 @@ class SessionMessageStore:
|
|
|
177
177
|
self.user_id = user_id
|
|
178
178
|
self.compressor = compressor or MessageCompressor()
|
|
179
179
|
self.repo = Repository(Message)
|
|
180
|
+
self._session_repo = Repository(Session, table_name="sessions")
|
|
181
|
+
|
|
182
|
+
async def _ensure_session_exists(
|
|
183
|
+
self,
|
|
184
|
+
session_id: str,
|
|
185
|
+
user_id: str | None = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
"""
|
|
188
|
+
Ensure session exists, creating it if necessary.
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
session_id: Session UUID from X-Session-Id header
|
|
192
|
+
user_id: Optional user identifier
|
|
193
|
+
"""
|
|
194
|
+
try:
|
|
195
|
+
# Check if session already exists by UUID
|
|
196
|
+
existing = await self._session_repo.get_by_id(session_id)
|
|
197
|
+
if existing:
|
|
198
|
+
return # Session already exists
|
|
199
|
+
|
|
200
|
+
# Create new session with the provided UUID as id
|
|
201
|
+
session = Session(
|
|
202
|
+
id=session_id, # Use the provided UUID as session id
|
|
203
|
+
name=session_id, # Default name to UUID, can be updated later
|
|
204
|
+
user_id=user_id or self.user_id,
|
|
205
|
+
tenant_id=self.user_id, # tenant_id set to user_id for scoping
|
|
206
|
+
)
|
|
207
|
+
await self._session_repo.upsert(session)
|
|
208
|
+
logger.info(f"Created session {session_id} for user {user_id or self.user_id}")
|
|
209
|
+
|
|
210
|
+
except Exception as e:
|
|
211
|
+
# Log but don't fail - session creation is best-effort
|
|
212
|
+
logger.warning(f"Failed to ensure session exists: {e}")
|
|
180
213
|
|
|
181
214
|
async def store_message(
|
|
182
215
|
self,
|
|
@@ -283,8 +316,10 @@ class SessionMessageStore:
|
|
|
283
316
|
"""
|
|
284
317
|
Store all session messages and return compressed versions.
|
|
285
318
|
|
|
319
|
+
Ensures session exists before storing messages.
|
|
320
|
+
|
|
286
321
|
Args:
|
|
287
|
-
session_id: Session
|
|
322
|
+
session_id: Session UUID
|
|
288
323
|
messages: List of messages to store
|
|
289
324
|
user_id: Optional user identifier
|
|
290
325
|
compress: Whether to compress messages (default: True)
|
|
@@ -296,6 +331,9 @@ class SessionMessageStore:
|
|
|
296
331
|
logger.debug("Postgres disabled, returning messages uncompressed")
|
|
297
332
|
return messages
|
|
298
333
|
|
|
334
|
+
# Ensure session exists before storing messages
|
|
335
|
+
await self._ensure_session_exists(session_id, user_id)
|
|
336
|
+
|
|
299
337
|
compressed_messages = []
|
|
300
338
|
|
|
301
339
|
for idx, message in enumerate(messages):
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Convert stored session messages to pydantic-ai native message format.
|
|
2
|
+
|
|
3
|
+
This module enables proper conversation history replay by converting our simplified
|
|
4
|
+
storage format into pydantic-ai's native ModelRequest/ModelResponse types.
|
|
5
|
+
|
|
6
|
+
Key insight: When we store tool results, we only store the result (ToolReturnPart).
|
|
7
|
+
But LLM APIs require matching ToolCallPart for each ToolReturnPart. So we synthesize
|
|
8
|
+
the ToolCallPart from stored metadata (tool_name, tool_call_id, tool_arguments).
|
|
9
|
+
|
|
10
|
+
Storage format (our simplified format):
|
|
11
|
+
{"role": "user", "content": "..."}
|
|
12
|
+
{"role": "assistant", "content": "..."}
|
|
13
|
+
{"role": "tool", "content": "{...}", "tool_name": "...", "tool_call_id": "...", "tool_arguments": {...}}
|
|
14
|
+
|
|
15
|
+
Pydantic-ai format (what the LLM expects):
|
|
16
|
+
ModelRequest(parts=[UserPromptPart(content="...")])
|
|
17
|
+
ModelResponse(parts=[TextPart(content="..."), ToolCallPart(...)]) # Call
|
|
18
|
+
ModelRequest(parts=[ToolReturnPart(...)]) # Result
|
|
19
|
+
|
|
20
|
+
Example usage:
|
|
21
|
+
from rem.services.session.pydantic_messages import session_to_pydantic_messages
|
|
22
|
+
|
|
23
|
+
# Load session history
|
|
24
|
+
session_history = await store.load_session_messages(session_id)
|
|
25
|
+
|
|
26
|
+
# Convert to pydantic-ai format
|
|
27
|
+
message_history = session_to_pydantic_messages(session_history)
|
|
28
|
+
|
|
29
|
+
# Use with agent.run()
|
|
30
|
+
result = await agent.run(user_prompt, message_history=message_history)
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import re
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from loguru import logger
|
|
38
|
+
from pydantic_ai.messages import (
|
|
39
|
+
ModelMessage,
|
|
40
|
+
ModelRequest,
|
|
41
|
+
ModelResponse,
|
|
42
|
+
SystemPromptPart,
|
|
43
|
+
TextPart,
|
|
44
|
+
ToolCallPart,
|
|
45
|
+
ToolReturnPart,
|
|
46
|
+
UserPromptPart,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _sanitize_tool_name(tool_name: str) -> str:
|
|
51
|
+
"""Sanitize tool name for OpenAI API compatibility.
|
|
52
|
+
|
|
53
|
+
OpenAI requires tool names to match pattern: ^[a-zA-Z0-9_-]+$
|
|
54
|
+
This replaces invalid characters (like colons) with underscores.
|
|
55
|
+
"""
|
|
56
|
+
return re.sub(r'[^a-zA-Z0-9_-]', '_', tool_name)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def session_to_pydantic_messages(
|
|
60
|
+
session_history: list[dict[str, Any]],
|
|
61
|
+
system_prompt: str | None = None,
|
|
62
|
+
) -> list[ModelMessage]:
|
|
63
|
+
"""Convert stored session messages to pydantic-ai ModelMessage format.
|
|
64
|
+
|
|
65
|
+
Handles the conversion of our simplified storage format to pydantic-ai's
|
|
66
|
+
native message types, including synthesizing ToolCallPart for tool results.
|
|
67
|
+
|
|
68
|
+
IMPORTANT: pydantic-ai only auto-adds system prompts when message_history is empty.
|
|
69
|
+
When passing message_history to agent.run(), you MUST include the system prompt
|
|
70
|
+
via the system_prompt parameter here.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
session_history: List of message dicts from SessionMessageStore.load_session_messages()
|
|
74
|
+
Each dict has: role, content, and optionally tool_name, tool_call_id, tool_arguments
|
|
75
|
+
system_prompt: The agent's system prompt (from schema description). This is REQUIRED
|
|
76
|
+
for proper agent behavior on subsequent turns, as pydantic-ai won't add it
|
|
77
|
+
automatically when message_history is provided.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
List of ModelMessage (ModelRequest | ModelResponse) ready for agent.run(message_history=...)
|
|
81
|
+
|
|
82
|
+
Note:
|
|
83
|
+
- System prompts ARE included as SystemPromptPart when system_prompt is provided
|
|
84
|
+
- Tool results require synthesized ToolCallPart to satisfy LLM API requirements
|
|
85
|
+
- The first message in session_history should be "user" role (from context builder)
|
|
86
|
+
"""
|
|
87
|
+
messages: list[ModelMessage] = []
|
|
88
|
+
|
|
89
|
+
# CRITICAL: Prepend agent's system prompt if provided
|
|
90
|
+
# This ensures the agent's instructions are present on every turn
|
|
91
|
+
# pydantic-ai only auto-adds system prompts when message_history is empty
|
|
92
|
+
if system_prompt:
|
|
93
|
+
messages.append(ModelRequest(parts=[SystemPromptPart(content=system_prompt)]))
|
|
94
|
+
logger.debug(f"Prepended agent system prompt ({len(system_prompt)} chars) to message history")
|
|
95
|
+
|
|
96
|
+
# Track pending tool results to batch them with assistant responses
|
|
97
|
+
# When we see a tool message, we need to:
|
|
98
|
+
# 1. Add a ModelResponse with ToolCallPart (synthesized)
|
|
99
|
+
# 2. Add a ModelRequest with ToolReturnPart (actual result)
|
|
100
|
+
|
|
101
|
+
i = 0
|
|
102
|
+
while i < len(session_history):
|
|
103
|
+
msg = session_history[i]
|
|
104
|
+
role = msg.get("role", "")
|
|
105
|
+
content = msg.get("content", "")
|
|
106
|
+
|
|
107
|
+
if role == "user":
|
|
108
|
+
# User messages become ModelRequest with UserPromptPart
|
|
109
|
+
messages.append(ModelRequest(parts=[UserPromptPart(content=content)]))
|
|
110
|
+
|
|
111
|
+
elif role == "assistant":
|
|
112
|
+
# Assistant text becomes ModelResponse with TextPart
|
|
113
|
+
# Check if there are following tool messages that should be grouped
|
|
114
|
+
tool_calls = []
|
|
115
|
+
tool_returns = []
|
|
116
|
+
|
|
117
|
+
# Look ahead for tool messages that follow this assistant message
|
|
118
|
+
j = i + 1
|
|
119
|
+
while j < len(session_history) and session_history[j].get("role") == "tool":
|
|
120
|
+
tool_msg = session_history[j]
|
|
121
|
+
tool_name = tool_msg.get("tool_name", "unknown_tool")
|
|
122
|
+
tool_call_id = tool_msg.get("tool_call_id", f"call_{j}")
|
|
123
|
+
tool_arguments = tool_msg.get("tool_arguments", {})
|
|
124
|
+
tool_content = tool_msg.get("content", "{}")
|
|
125
|
+
|
|
126
|
+
# Parse tool content if it's a JSON string
|
|
127
|
+
if isinstance(tool_content, str):
|
|
128
|
+
try:
|
|
129
|
+
tool_result = json.loads(tool_content)
|
|
130
|
+
except json.JSONDecodeError:
|
|
131
|
+
tool_result = {"raw": tool_content}
|
|
132
|
+
else:
|
|
133
|
+
tool_result = tool_content
|
|
134
|
+
|
|
135
|
+
# Sanitize tool name for OpenAI API compatibility
|
|
136
|
+
safe_tool_name = _sanitize_tool_name(tool_name)
|
|
137
|
+
|
|
138
|
+
# Synthesize ToolCallPart (what the model "called")
|
|
139
|
+
tool_calls.append(ToolCallPart(
|
|
140
|
+
tool_name=safe_tool_name,
|
|
141
|
+
args=tool_arguments if tool_arguments else {},
|
|
142
|
+
tool_call_id=tool_call_id,
|
|
143
|
+
))
|
|
144
|
+
|
|
145
|
+
# Create ToolReturnPart (the actual result)
|
|
146
|
+
tool_returns.append(ToolReturnPart(
|
|
147
|
+
tool_name=safe_tool_name,
|
|
148
|
+
content=tool_result,
|
|
149
|
+
tool_call_id=tool_call_id,
|
|
150
|
+
))
|
|
151
|
+
|
|
152
|
+
j += 1
|
|
153
|
+
|
|
154
|
+
# Build the assistant's ModelResponse
|
|
155
|
+
response_parts = []
|
|
156
|
+
|
|
157
|
+
# Add tool calls first (if any)
|
|
158
|
+
response_parts.extend(tool_calls)
|
|
159
|
+
|
|
160
|
+
# Add text content (if any)
|
|
161
|
+
if content:
|
|
162
|
+
response_parts.append(TextPart(content=content))
|
|
163
|
+
|
|
164
|
+
# Only add ModelResponse if we have parts
|
|
165
|
+
if response_parts:
|
|
166
|
+
messages.append(ModelResponse(
|
|
167
|
+
parts=response_parts,
|
|
168
|
+
model_name="recovered", # We don't store model name
|
|
169
|
+
))
|
|
170
|
+
|
|
171
|
+
# Add tool returns as ModelRequest (required by LLM API)
|
|
172
|
+
if tool_returns:
|
|
173
|
+
messages.append(ModelRequest(parts=tool_returns))
|
|
174
|
+
|
|
175
|
+
# Skip the tool messages we just processed
|
|
176
|
+
i = j - 1
|
|
177
|
+
|
|
178
|
+
elif role == "tool":
|
|
179
|
+
# Orphan tool message (no preceding assistant) - synthesize both parts
|
|
180
|
+
tool_name = msg.get("tool_name", "unknown_tool")
|
|
181
|
+
tool_call_id = msg.get("tool_call_id", f"call_{i}")
|
|
182
|
+
tool_arguments = msg.get("tool_arguments", {})
|
|
183
|
+
tool_content = msg.get("content", "{}")
|
|
184
|
+
|
|
185
|
+
# Parse tool content
|
|
186
|
+
if isinstance(tool_content, str):
|
|
187
|
+
try:
|
|
188
|
+
tool_result = json.loads(tool_content)
|
|
189
|
+
except json.JSONDecodeError:
|
|
190
|
+
tool_result = {"raw": tool_content}
|
|
191
|
+
else:
|
|
192
|
+
tool_result = tool_content
|
|
193
|
+
|
|
194
|
+
# Sanitize tool name for OpenAI API compatibility
|
|
195
|
+
safe_tool_name = _sanitize_tool_name(tool_name)
|
|
196
|
+
|
|
197
|
+
# Synthesize the tool call (ModelResponse with ToolCallPart)
|
|
198
|
+
messages.append(ModelResponse(
|
|
199
|
+
parts=[ToolCallPart(
|
|
200
|
+
tool_name=safe_tool_name,
|
|
201
|
+
args=tool_arguments if tool_arguments else {},
|
|
202
|
+
tool_call_id=tool_call_id,
|
|
203
|
+
)],
|
|
204
|
+
model_name="recovered",
|
|
205
|
+
))
|
|
206
|
+
|
|
207
|
+
# Add the tool return (ModelRequest with ToolReturnPart)
|
|
208
|
+
messages.append(ModelRequest(
|
|
209
|
+
parts=[ToolReturnPart(
|
|
210
|
+
tool_name=safe_tool_name,
|
|
211
|
+
content=tool_result,
|
|
212
|
+
tool_call_id=tool_call_id,
|
|
213
|
+
)]
|
|
214
|
+
))
|
|
215
|
+
|
|
216
|
+
elif role == "system":
|
|
217
|
+
# Skip system messages - pydantic-ai handles these via Agent.system_prompt
|
|
218
|
+
logger.debug("Skipping system message in session history (handled by Agent)")
|
|
219
|
+
|
|
220
|
+
else:
|
|
221
|
+
logger.warning(f"Unknown message role in session history: {role}")
|
|
222
|
+
|
|
223
|
+
i += 1
|
|
224
|
+
|
|
225
|
+
logger.debug(f"Converted {len(session_history)} stored messages to {len(messages)} pydantic-ai messages")
|
|
226
|
+
return messages
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def audit_session_history(
|
|
230
|
+
session_id: str,
|
|
231
|
+
agent_name: str,
|
|
232
|
+
prompt: str,
|
|
233
|
+
raw_session_history: list[dict[str, Any]],
|
|
234
|
+
pydantic_messages_count: int,
|
|
235
|
+
) -> None:
|
|
236
|
+
"""
|
|
237
|
+
Dump session history to a YAML file for debugging.
|
|
238
|
+
|
|
239
|
+
Only runs when DEBUG__AUDIT_SESSION=true. Writes to DEBUG__AUDIT_DIR (default /tmp).
|
|
240
|
+
Appends to the same file for a session, so all agent invocations are in one place.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
session_id: The session identifier
|
|
244
|
+
agent_name: Name of the agent being invoked
|
|
245
|
+
prompt: The prompt being sent to the agent
|
|
246
|
+
raw_session_history: The raw session messages from the database
|
|
247
|
+
pydantic_messages_count: Count of converted pydantic-ai messages
|
|
248
|
+
"""
|
|
249
|
+
from ...settings import settings
|
|
250
|
+
|
|
251
|
+
if not settings.debug.audit_session:
|
|
252
|
+
return
|
|
253
|
+
|
|
254
|
+
try:
|
|
255
|
+
import yaml
|
|
256
|
+
from pathlib import Path
|
|
257
|
+
from ...utils.date_utils import utc_now, to_iso
|
|
258
|
+
|
|
259
|
+
audit_dir = Path(settings.debug.audit_dir)
|
|
260
|
+
audit_dir.mkdir(parents=True, exist_ok=True)
|
|
261
|
+
audit_file = audit_dir / f"{session_id}.yaml"
|
|
262
|
+
|
|
263
|
+
# Create entry for this agent invocation
|
|
264
|
+
entry = {
|
|
265
|
+
"timestamp": to_iso(utc_now()),
|
|
266
|
+
"agent_name": agent_name,
|
|
267
|
+
"prompt": prompt,
|
|
268
|
+
"raw_history_count": len(raw_session_history),
|
|
269
|
+
"pydantic_messages_count": pydantic_messages_count,
|
|
270
|
+
"raw_session_history": raw_session_history,
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
# Load existing data or create new
|
|
274
|
+
existing_data: dict[str, Any] = {"session_id": session_id, "invocations": []}
|
|
275
|
+
if audit_file.exists():
|
|
276
|
+
with open(audit_file) as f:
|
|
277
|
+
loaded = yaml.safe_load(f)
|
|
278
|
+
if loaded:
|
|
279
|
+
# Ensure session_id is always present (backfill if missing)
|
|
280
|
+
existing_data = {
|
|
281
|
+
"session_id": loaded.get("session_id", session_id),
|
|
282
|
+
"invocations": loaded.get("invocations", []),
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
# Append this invocation
|
|
286
|
+
existing_data["invocations"].append(entry)
|
|
287
|
+
|
|
288
|
+
with open(audit_file, "w") as f:
|
|
289
|
+
yaml.dump(existing_data, f, default_flow_style=False, allow_unicode=True)
|
|
290
|
+
logger.info(f"DEBUG: Session audit updated: {audit_file}")
|
|
291
|
+
except Exception as e:
|
|
292
|
+
logger.warning(f"DEBUG: Failed to dump session audit: {e}")
|